簡體   English   中英

如何索引多個項目位置並從具有這些位置的另一個列表中獲取項目?

[英]How to index multiple item positions and get items from another list with those positions?

names = ['vik', 'zed', 'loren', 'tal', 'yam', 'jay', 'alex', 'gad', 'dan', 'hed']
cities = ['NY', 'NY', 'SA', 'TNY', 'LA', 'SA', 'SA', 'NY', 'SA', 'LA']
ages = ['28', '26', '26', '31', '28', '23', '29', '31', '27', '41']

如何創建一個包含所有 SA 人員姓名的新列表?

我嘗試獲取所有“SA”位置,然后打印名稱列表中的相同位置,

pos = [i for i in range(len(names)) if cities[i] == 'SA']
print(names[pos]) 

返回以下錯誤:

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

我也嘗試過遍歷城市中的位置,然后一個一個地做幾乎相同的事情,但我仍然無法放入列表

pos = [i for i in range(len(names)) if cities[i] == 'SA']
x = 1
for i in pos:
     x+=1

您可以 zip 將名稱年齡和城市放在一起,然后使用列表理解按城市過濾這些名稱

 [(a,b,c) for a,b,c in zip(names, cities, ages) if b == "SA"]

返回

[('loren', 'SA', '26'), ('jay', 'SA', '23'), ('alex', 'SA', '29'), ('dan', 'SA', '27')]

枚舉城市列表,以便您也獲得它們的索引,並在城市匹配時收集名稱:

names = ['vik', 'zed', 'loren', 'tal', 'yam', 'jay', 'alex', 'gad', 'dan', 'hed']
cities = ['NY', 'NY', 'SA', 'TNY', 'LA', 'SA', 'SA', 'NY', 'SA', 'LA'] 
  
print( [names[idx] for idx,c in enumerate(cities) if c == "SA"] ) 

Output:

['loren', 'jay', 'alex', 'dan']

請參閱: enumerate python.org

如何創建一個包含所有 SA 人員姓名的新列表?

Oneliner(但問題可能不清楚)使用zip和帶有過濾器的列表理解

lst = [n for n, c in zip(names, cities) if c == 'SA']
print(lst)

輸出:

['loren', 'jay', 'alex', 'dan']

解釋

oneliner 相當於:

lst = []
for name, city in zip(names, cities):
    if city == 'SA':
        lst.append(name)
print(lst)

zip迭代namescities列表,生成“(<a_name>, <a_city>)”形式的元組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM