[英]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.我想过滤并获取第二项 object 的所有值的列表,其中第一项是“测试”字符串。 So the output will be like:
所以 output 会像:
['testval1','testval2','testval3','testval4']
Manage to get the test elements with Output = list(filter(lambda x:'test' in x, conditions)).使用 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?
如何在没有循环的情况下再次获取第二个 obj 元素的值?
>>> 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
) (假设您的列表是
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.列表推导是通过在列表名称后添加 if 来过滤此类列表的好方法。
or you can do it by filter and map或者你可以通过过滤器和 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他们都将 output
['testval1', 'testval2', 'testval3', 'testval4']
using Setdefault
使用
Setdefault
output=[]
for item,dict in li:
if item == 'test':
var = dict.setdefault('key',{})
output.append(var)
print(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.