Reputation: 537
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 third section of every list inside the list of list.
example, I want python to print the element represented by letter 'G' for every item in the list of list.
output = [4.2,3.4]
[8.7,5.4]
Here's what I've tried:
L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = []
for line in L:
if line[0][2] == 'G'
newList.append([float(i) for i in line[0:2]])
print(newList)
my error would be on line 5 as I'm not sure if i am able to do it this way. Regards.
Upvotes: 3
Views: 3034
Reputation: 517
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
Upvotes: 2
Reputation: 48077
You may create a function to return sub-lists based on the element using an list comprehension expression along with the usage of map
as:
def get_element_by_alpha(alpha, data_list):
# v map returns generator object in Python 3.x,hence type-cast to `list`
return [list(map(float, s[:2])) for s in data_list if s[2]==alpha]
# ^ type-cast the number string to `float` type
Sample Runs:
>>> my_list = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
>>> get_element_by_alpha('G', my_list)
[[4.2, 3.4], [8.7, 5.4]]
>>> get_element_by_alpha('H', my_list)
[[2.4, 1.2]]
>>> get_element_by_alpha('A', my_list) # 'A' not in the list
[]
Upvotes: 0
Reputation: 2047
@Electric your edited code.
L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = []
# line = ['4.2','3.4','G']
for line in L:
if line[2] == 'G': # ':' was missing.
newList.append(line[:2]) # line[:2] => ['4.2','3.4']
print(newList)
Upvotes: 0
Reputation: 34
A list comprehension will do this:
newList = [[float(j) for j in i[:-1]] for i in L if i[2]=='G']
Upvotes: 0
Reputation: 27466
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']
Upvotes: 0
Reputation: 1947
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]]
Upvotes: 1
Reputation: 92854
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']]
Upvotes: 3