简体   繁体   中英

Python printing the first item of each nested list with a single print command

I would like to know why does this code does not output the first item of each nested list. I have found an alternative that works but I would like to know why this one does not output the desired output.

tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'], 
['dogs', 'cats', 'moose', 'goose']]
print(tableData[:][1])

tableData[:] returns the entire list. So tableData[:][1] only returns the second element in tableData , which is your list ['Alice', 'Bob', ...] .

You can get the first element of every list using a list comprehension:

print [sublist[0] for sublist in tableData]

The above code is equivalent to this:

first_elements = []
for sublist in tableData:
    first_elements.append(sublist[0])
print first_elements

This doesn't work because tableData[:] returns the whole list. It's an equivalent of tableData (without [:] ). As posted Josh, you can use a list comprehension to get the elements you want.

Because tableData[:] means the whole list, which is just a copy of tableData . So tableData[:][1] is the 1-th (second) item in tableData , which is ['Alice', 'Bob', 'Carol', 'David'] in your code.

You should use [0] this will get the first element in the list then you do a for loop to go through every element in the list for example:

tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'], 
['dogs', 'cats', 'moose', 'goose']]
for i in tableData:
    print(i[0])

I hope this makes sense.

print([i[0] for i in tableData])

here is the code for this which gives clean space seperated output print(*[i[0] for i in tableData]) In Your the tableData[:] will evaluate to TableData then TableData[1] will evaluate to ['Alice', 'Bob', 'Carol', 'David']

[ from: to] operator means slicing - > returns new string.

For example:

lst = [0, 1, 2, 3] 
lst[0:2] #will return [0, 1]

[: ] will return the list as it is.

So if you want to access the first value type: lst[0] In your code you typed tableData[1] so it returns the second index because the indexes starts from Zero

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