简体   繁体   中英

list.index() not quite working

I'm using this piece of code for a small program I need to design for a friend. The problem is can't quite get it to work.

I am designing a program that uses list for vegetables and fruits. For example my list is:

smallist = [["apple", 2], ["banana", 3], ["strawberry",1]]
item = input("Please give the name of the fruit\n\n")

smallist.index(item)
print (smallist)

The problem is when I then try to find the index of lets say the apple. I just say that the apple does not exist.

smallist.index(item)
ValueError: 'apple' is not in list

I can't figure out why it won't show me the apple with its value which in this case would be 2

apple is not in smallist . It is in a nested list contained inside of smallist .

You'll have to search for it with a loop:

for i, nested in enumerate(smallist):
    if item in nested:
        print(i)
        break

Here enumerate() creates a running index for us while looping over smallist so we can print the index where it was found.

If what you wanted to do was print the other value we don't need the index:

for name, count in smallist:
    if name == item:
        print(count)
        break

But it'd be easier to use a dictionary here:

small_dict = dict(smallist)
print(small_dict.get(item, 'Not found'))

"apple" isn't in smallist , ["apple", 2] is.

Your data would fit much better into a dictionary:

smaldict = {'apple': 2, 'banana': 3, 'strawberry': 1}

item = input("Please give the name of the fruit\n\n")
if item in smaldict:
    print(smaldict[item])
else:
    print('"{item}" is not in the dictionary.'.format(item=item))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM