简体   繁体   中英

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?

I tried getting all 'SA' positions and then print the same positions that are in the names list,

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

 [(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:

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

See: enumerate on python.org

How do i create a new list with names of all the people from SA?

Oneliner (but maybe the question is unclear) using zip and list comprehension with a filter

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:

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>)"

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