我正在尝试获取每个列表中第二个值的列表。
例如'val2':
['xe-1/2/1.322','xe-9/1/2']
原始列表如下所示:
l = [('val1', 'ae4.0'),
('val1', 'xe-9/1/7.0'),
('val1', 'xe-1/2/1.1151'),
('val2', 'xe-1/2/1.322'),
('val2', 'xe-9/1/2'),
('val3', 'xe-9/1/2'),
('val3', 'xe-1/2/1'),
('val3', 'xe-1/2/1.748')]
答案 0 :(得分:3)
如果第一个元素与val2
匹配,则可以使用列表推导并从元组中返回第二个元素:
l = [('val1', 'ae4.0'), ('val1', 'xe-9/1/7.0'), ('val1', 'xe-1/2/1.1151'),
('val2', 'xe-1/2/1.322'), ('val2', 'xe-9/1/2'), ('val3', 'xe-9/1/2'),
('val3', 'xe-1/2/1'), ('val3', 'xe-1/2/1.748')]
[i[1] for i in l if i[0] == 'val2']
# ['xe-1/2/1.322', 'xe-9/1/2']
答案 1 :(得分:1)
您可以创建一个以键为第一个值的字典:
l = [('val1', 'ae4.0'), ('val1', 'xe-9/1/7.0'), ('val1', 'xe-1/2/1.1151'),
('val2', 'xe-1/2/1.322'), ('val2', 'xe-9/1/2'), ('val3', 'xe-9/1/2'),
('val3', 'xe-1/2/1'), ('val3', 'xe-1/2/1.748')]
s = {}
for elem in l:
if elem[0] not in s:
s[elem[0]] = []
s[elem[0]].append( elem[1])
print(s['val2'])