Filter List Based On The Element In Nested List At Specific Index
I have a list of list containing: [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']] and i want to obtain the value from the list of list by referring to the alphabet in the
Solution 1:
Simple list comprehension:
L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = [l[0:2] for l in L if l[2] == 'G']
print(newList)
The output:
[['4.2', '3.4'], ['8.7', '5.4']]
Solution 2:
I would suggest using a collections.defaultdict
, as a multi-value dictionary:
from collections import defaultdict
d = defaultdict(list)
for x in L:
d[x[2]].append(x[:2])
Now you can use d['G']
to get what you wanted, but also d['H']
to get the result for 'H'
!
Edit: Source append multiple values for one key in Python dictionary
Solution 3:
There are 2 issues in your code,
1. line = ['4.2', '3.4', 'G'] for 1st iteration
hence to check for'G', look out for line[2] == 'G' instead of line[0][3] == 'G'2. use 'G' instead off 'house'.
>>> for line in L:
... if line[2] == 'G':
... newList.append([float(i) for i in line[0:2]])
... >>> newList
[[4.2, 3.4], [8.7, 5.4]]
Solution 4:
you can use a dictionary by iterating the list of lists.
lst = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
dict1 = {}
for l in lst:
if l[2] in dict1.keys():
dict1[l[2]].append(l[0:2])
else:
dict1[l[2]] = [l[0:2]]
print l[0:2]
print dict1['G']
Solution 5:
A list comprehension will do this:
newList = [[float(j) for j in i[:-1]]for i in L if i[2]=='G']
Post a Comment for "Filter List Based On The Element In Nested List At Specific Index"