简体   繁体   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']

How do I create a new list with names of all the people from SA?如何创建一个包含所有 SA 人员姓名的新列表?

I tried getting all 'SA' positions and then print the same positions that are in the names list,我尝试获取所有“SA”位置,然后打印名称列表中的相同位置,

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

Returns the following error:返回以下错误:

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

I've also attempted to loop over the positions in cities and then do pretty much the same but one by one, but i still wasn't able to put in a list我也尝试过遍历城市中的位置,然后一个一个地做几乎相同的事情,但我仍然无法放入列表

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

You can zip the names ages and cities together then use a list comprehension to filter those by city您可以 zip 将名称年龄和城市放在一起,然后使用列表理解按城市过滤这些名称

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

returns返回

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

Enumerate the list of cities so you get their index as well, and collect the names if the city matches:枚举城市列表,以便您也获得它们的索引,并在城市匹配时收集名称:

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: Output:

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

See: enumerate on python.org请参阅: enumerate python.org

How do i create a new list with names of all the people from SA?如何创建一个包含所有 SA 人员姓名的新列表?

Oneliner (but maybe the question is unclear) using zip and list comprehension with a filter Oneliner(但问题可能不清楚)使用zip和带有过滤器的列表理解

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

Ouput:输出:

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

Explaination解释

The oneliner is equivalent to: oneliner 相当于:

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

zip iterates over the names and cities lists in parallel, producing tuples in the form "(<a_name>, <a_city>)" zip迭代namescities列表,生成“(<a_name>, <a_city>)”形式的元组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM