简体   繁体   中英

When I try to call out specific data in a for loop The error says: list indices must be integers or slices, not tuple

I'm using nested lists and while printing certain values in a list it is giving me an error,

TypeError: list indices must be integers or slices, not tuple

I'm new to Python and I've been using nested loops. I don't know what this error means and I don't have friends that code. I've tried troubleshooting but I still can't figure it out.

This is the portion of my code where I am getting an issue

chaal = [1, 4.55]
chicken = [2, 19.80]
onionpaste = [1, 2.50]
garlicpaste = [1, 2.50]
onion = [1, 2.95]
garlic = [1, 2.95]
ginger = [1, 4.60]
masala = [1, 5.70]
ghee = [1, 4.40]
ingredients = [
    ["chaal", chaal],
    ["whole chicken", chicken],
    ["onion paste", onionpaste],
    ["garlic paste", garlicpaste],
    ["onion", onion],
    ["garlic", garlic],
    ["ginger", ginger],
    ["garam masala", masala],
    ['Ghee', ghee]
]

print("These are the ingredients you will need for the dish:")

for i in range(len(ingredients)):
    print(ingredients[i, 0])

I expect the output to print out the name of each ingredient in the list.

Python does not have true multi-dimensional arrays, so you can't write a two-index expression like [i, 0] . Instead you are dealing with a list of lists; dereference the main list, eg ingredients[i] , to get a list; then you can index into this list with a second index, ie ingredients[i][0] . This does in one step the equivalent of

temp = ingredients[i]
print(temp[0])

Solution 1:

for i in range(len(ingredients)):  # iterate by index
    print(ingredients[i][0])

or:

for i in ingredients:  # iterate by element
    print(i[0])

Output of solution 1:

chaal
whole chicken
onion paste
garlic paste
onion
garlic
ginger
garam masala
Ghee

Solution 2:

import numpy as np
a = np.array(ingredients)
print(a[:,:1])  # slicing by numpy array

Output of solution 2:

[['chaal']
 ['whole chicken']
 ['onion paste']
 ['garlic paste']
 ['onion']
 ['garlic']
 ['ginger']
 ['garam masala']
 ['Ghee']]

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