I have two lists:
x = ['1','5','X','9']
y = ['X','9','9P']
which I have combined like this:
z = [x,y]
print(z)
So, "z" is a list of two lists and it looks like this:
[['1', '5', 'X', '9'], ['X', '9', '9P']]
I have this dictionary:
delqType = {
'1' : 0,
'2' : 3,
'3' : 4,
'4' : 5,
'5' : 6,
'7' : 19,
'8' : 21,
'8A' : 20,
'8P' : 16,
'9' : 22,
'9B' : 18,
'9P' : 15,
'UR' : 23,
'X' : -99999
}
I want to apply the dictionary delqType to the list "z" in order to get this new list (called "t") that looks like:
[[0, 6, -99999, 22], [-99999, 22, 15]]
I have tried this code:
t = []
for i in range(len(z)):
for j in range(len(z[i])):
t.append(delqType[z[i][j]])
next
But I get one list (and not a list of two lists as I want):
[0, 6, -99999, 22, -99999, 22, 15]
How can I get a list of two lists containing the elements after they have been transformed using the dictionary?
CodePudding user response:
You can use nested list comprehension.
t = [[delqType[i] for i in list_i] for list_i in z]
print(t)
[[0, 6, -99999, 22], [-99999, 22, 15]]
CodePudding user response:
You should created the nested lists in t
, one for each nested list of z
. In addition it will be simpler to iterate the items instead of the indices:
t = []
for sub in z:
t.append([])
for item in sub:
t[-1].append(delqType[item])
Another nice way is to use the itemgetter
operator to map the list of keys to the list of values:
from operator import itemgetter
t = [itemgetter(*sub)(delqType) for sub in z]
CodePudding user response:
As you want to get a 2 dimensions list, you need to append a list inside your first for
loop.
(But also, please use the for
loop to directly extract values, instead of using indices !)
So, this would look like:
t = []
for sublist in z:
new_sublist = []
for key in sublist:
newlist.append(...)
t.append(new_sublist)
I let to you to fill the internals of the deepest for
loop, as an exercise, to ensure you got it correctly :-)
Side note: your code sample is not correct, as there is no next
keyword in Python!! Please be sure to provide the exact code you executed.