Allow zip function to map 1D to 2D array
Allow zip function to map 1D to 2D array
Suppose I have these two arrays where one of them is 2D.
letters = ['a', 'b', 'c', 'd']
values = [[1, 2, 3, 4], [10, 20, 30, 40]]
Now, I want to have the following assignment so that letters
matches every list in the values
, something like this:
letters
values
a 1
b 2
c 3
d 4
a 10
b 20
c 30
d 40
The following code works only if both letters
and values
are 1D
. How can I fix it to achieve my desired assignment above?
letters
values
1D
letters = ['a', 'b', 'c', 'd']
values = [[1, 2, 3, 4], [10, 20, 30, 40]]
for l, v in zip(letters, values):
print(l,v)
Thank you
for l, v in zip([letters]*len(values), values)
3 Answers
3
You need to iterate over the data twice:
letters = ['a', 'b', 'c', 'd']
values = [[1, 2, 3, 4], [10, 20, 30, 40]]
for v in values:
for a, b in zip(letters, v):
print(f'{a} {b}')
print()
Output:
a 1
b 2
c 3
d 4
a 10
b 20
c 30
d 40
If it is useful to you to have tuples of the letters and the numbers they match, you might consider this:
for t in zip(letters, *values):
print(t)
output:
('a', 1, 10)
('b', 2, 20)
('c', 3, 30)
('d', 4, 40)
If your goal is to associate the letters with each of the corresponding values from the value lists, this is faster than looping over letters
once for each list in values
.
letters
values
You can also just use zip twice:
letters = ['a', 'b', 'c', 'd']
values = [[1, 2, 3, 4], [10, 20, 30, 40]]
out = list(zip(letters, values[0])) + list(zip(letters, values[1]))
or for a more robust solution you could iterate through the lists in values
letters = ['a', 'b', 'c', 'd']
values = [[1, 2, 3, 4], [10, 20, 30, 40]]
out =
[out + list(zip(letters, v)) for v in values]
Edit: Apologies, the accepted answer already does this.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
If memory / performance isn't a concern, you can use
for l, v in zip([letters]*len(values), values)
.– jpp
Jun 29 at 18:07