Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you use .index for 2D arrays (without using numpy)?

So I’ve been tring to use .index with 2D arrays just so I can do some tests on my code, but it just comes up with an error saying that the value which is in the list actually isn’t.
For example, from one project (where i was trying to revise network layering whilst practicing some coding), I tried doing this but didnt work:

answers = [['Application Layer','HTTP','HTTPS','SMTP','IMAP','FTP'],['Transport Layer','TCP','UDP'],['Network Layer','ARP','IP','ICMP'],['Data Link layer']]
correct = 0
incorrect = 0

qs = answers[randint(0,3)][0]
print(answers.index(qs))
print(qs)

Example from code

As you can see, I’m trying to get back the value of ‘qs’ by using index but no luck.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve seen a few other posts saying to use numpy, but how would I do this without using numpy?

>Solution :

You can do it like this.

answers = [['Application Layer','HTTP','HTTPS','SMTP','IMAP','FTP'],['Transport Layer','TCP','UDP'],['Network Layer','ARP','IP','ICMP'],['Data Link layer']]
correct = 0
incorrect = 0

qs = answers[randint(0,3)][0]

for i, answer in enumerate(answers):
    if qs in answer:
        print(i)
        break

print(qs)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading