Lst = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]]
What I need is-
a1,b1,c1 = (1,2,3)
a2,b2,c2 = (201,202,203)
and so on ...
Lst = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]]
What I need is-
a1,b1,c1 = (1,2,3)
a2,b2,c2 = (201,202,203)
and so on ...
You are a looking to map values to coordinates. Well, you can just access directly via L[outer_list_idx][inner_list_idx]
with a couple of list operations.
You can use a dictionary for a variable number of variables. This removes the need to define a large number of variables explicitly.
Using letters has the obvious limitation of allowing a maximum of 26 lists. If this is what you wish, there's no need to define letters explicitly, use string.ascii_lowercase
:
from string import ascii_lowercase
L = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]]
m, n = len(L), len(L[0])
d = {(ascii_lowercase[j], i+1): L[i][j] for i in range(m) for j in range(n)}
print(d)
{('a', 1): 1, ('b', 1): 2, ('c', 1): 3,
('a', 2): 201, ('b', 2): 202, ('c', 2): 203,
('a', 3): 3, ('b', 3): 1, ('c', 3): 4,
('a', 4): 591, ('b', 4): 2019, ('c', 4): 3.14}
Then access via tuple keys. So, to retrieve the 2nd value from the 3rd list, you can use d[('b', 3)]
.
The example is can be solved with simple tuple unpacking. You can use zip
to pair your values:
lst = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]]
((a1, b1, c1), (a2, b2, c2)), _ = zip(lst[::2], lst[1::2])
print(a1, b1, c1)
print(a2, b2, c2)
This will print:
1 2 3
201 202 203
If you want next values, you can do:
_, ((a1, b1, c1), (a2, b2, c2)) = zip(lst[::2], lst[1::2])
print(a1, b1, c1)
print(a2, b2, c2)
Output:
3 1 4
591 2019 3.14
You can use itertools.chain.from_iterable()
for this:
t = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]]
from itertools import chain
a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4 = chain.from_iterable(t) # flattens the list of lists
print(a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4)
Output:
1 2 3 201 202 203 3 1 4 591 2019 3.14
You need to know the dimensions of the list beforehand and the variablenames. I would probably just use the original list ...
Do you just need the values? Then like that:
Lst = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]]
for k in Lst:
a, b, c = k
print(a, b, c)