简体   繁体   中英

Search list of tuples according to first element and get list of second element values

Lets say i have the following list of tuples:

[('test', {'key': 'testval1' }),
 ('test', {'key': 'testval2' }),
 ('test', {'key': 'testval3' }),
 ('test', {'key': 'testval4' }),
 ('foo', {'key': 'testval5' }),
 ('oof', {'key': 'testval6' }),
 ('qux', {'key': 'testval7' }),
 ('qux', {'key': 'testval8' })]

I want to filter and get a list of all values of second item object that have first item the 'test' string. So the output will be like:

['testval1','testval2','testval3','testval4']

Manage to get the test elements with Output = list(filter(lambda x:'test' in x, conditions)). But this returns me another list of tuples. How can i get the values of the second obj element without loop again?

>>> elements = [('test', {'key': 'testval1' }),
...  ('test', {'key': 'testval2' }),
...  ('test', {'key': 'testval3' }),
...  ('test', {'key': 'testval4' }),
...  ('foo', {'key': 'testval5' }),
...  ('oof', {'key': 'testval6' }),
...  ('qux', {'key': 'testval7' }),
...  ('qux', {'key': 'testval8' })]
>>> [d['key'] for (s, d) in elements if s == 'test']
['testval1', 'testval2', 'testval3', 'testval4']

Using a single comprehension should do it:

[b['key'] for a, b in data if a == 'test']

(Assuming your list is data )

you can do

a = [('test', {'key': 'testval1' }),  ('test', {'key': 'testval2' }),  ('test', {'key': 'testval3' }),  ('test', {'key': 'testval4' }),  ('foo', {'key': 'testval5' }),  ('oof', {'key': 'testval6' }),  ('qux', {'key': 'testval7' }),  ('qux', {'key': 'testval8' })]
print([i[1]['key'] for i in a if i[0] == 'test'])

list comprehension is a great method to filter such lists by adding the if after the list name.
or you can do it by filter and map

print([*map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))])

or

print(list(map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))))

All of them will output

['testval1', 'testval2', 'testval3', 'testval4']

using Setdefault

output=[]

for item,dict in  li:
   if item == 'test':
       var = dict.setdefault('key',{})
       output.append(var)

print(output)

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