![](/img/trans.png)
[英]Returning first element of a tuple after finding the tuple according to the second value in a list of tuples
[英]Search list of tuples according to first element and get list of second element values
假設我有以下元組列表:
[('test', {'key': 'testval1' }),
('test', {'key': 'testval2' }),
('test', {'key': 'testval3' }),
('test', {'key': 'testval4' }),
('foo', {'key': 'testval5' }),
('oof', {'key': 'testval6' }),
('qux', {'key': 'testval7' }),
('qux', {'key': 'testval8' })]
我想過濾並獲取第二項 object 的所有值的列表,其中第一項是“測試”字符串。 所以 output 會像:
['testval1','testval2','testval3','testval4']
使用 Output = list(filter(lambda x:'test' in x, conditions)) 設法獲取測試元素。 但這會給我返回另一個元組列表。 如何在沒有循環的情況下再次獲取第二個 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']
使用單一的理解應該做到這一點:
[b['key'] for a, b in data if a == 'test']
(假設您的列表是data
)
你可以做
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'])
列表推導是通過在列表名稱后添加 if 來過濾此類列表的好方法。
或者你可以通過過濾器和 map
print([*map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))])
或者
print(list(map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))))
他們都將 output
['testval1', 'testval2', 'testval3', 'testval4']
使用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.