![](/img/trans.png)
[英]How can I iterate through a list within the dictionary and run the command for each index?
[英]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)`
打印出“喬布斯”、“牛頓”、“愛因斯坦”
這是 Python 中列表推導非常好的地方:
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]
print([group[0] for group in groups])
結果:
['Jobs', 'Newton', 'Einstein']
如果您只想對每個單獨的第一個條目做一些事情,您當然只需這樣做:
for group in groups:
print(group[0])
或者,沒有索引:
for (name, *__) in groups:
print(name)
您可以像這樣使用列表理解:
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]
groups_only_first = [x[0] for x in groups]
print(groups_only_first)
您還可以使用unpack 運算符對子列表進行解包,並使用zip
創建一個可迭代的元組。 由於您需要每個列表中的第一個元素,因此您需要 zip object 的第一個元素。 您不能索引 zip object 因此您將其轉換為tuple
並獲取第一個元素。
x = tuple(zip(*[["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]))[0]
print(x)
Output:
('Jobs', 'Newton', 'Einstein')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.