简体   繁体   中英

How can I iterate through a 2D list to just get the first index within each list?

groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]
 
# This outer loop will iterate over each list in the groups list
for group in groups:
  # This inner loop will go through each name in each list
  for name in group:
    print(name)`

Print out 'Jobs', 'Newton', 'Einstein'

This is where list comprehensions are really nice in Python:

groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]

print([group[0] for group in groups])

Result:

['Jobs', 'Newton', 'Einstein']

If you just want to do something with each individual first entry, you of course just do this:

for group in groups:
    print(group[0])

Or, without the indexing:

for (name, *__) in groups:
    print(name)

You can use list comprehension like this:

groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]
groups_only_first = [x[0] for x in groups]
print(groups_only_first)

You can also use the unpack operator to unpack the sublists and use zip to create an iterable of tuples. Since you want the first elements in each list, you want the first element of the zip object. You can't index a zip object so you cast it to tuple and take the first element.

x = tuple(zip(*[["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]))[0]    
print(x)

Output:

('Jobs', 'Newton', 'Einstein')

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