I´m trying to obtain a list of the second value inside each list.
For example for 'val2':
['xe-1/2/1.322','xe-9/1/2']
The original list looks something like this:
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')]
You can just use a list comprehension and return the second element from the tuples if the first one matches with 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']
You can create a dictionary with keys as the first value :
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'])
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.