Convert list elements to be the list of lists of another list

Viewed 74

Appreciate your help, this is a question about list of lists.
Given lists:\

g = [[] for _ in range(5)]
a = [1,2,3,4]
b = [37100,3710,371,37,0]

I need the result to be g = [[37100,1],[3710,2],[371,3],[37,4],[0]], I tried to use nested for loops, but that is not working, below is my code:


    g = [[] for _ in range(5)]
    a=[1,2,3,4]
    b = [37100,3710,371,37,0]
    for i in range(len(b)):
      g[i].append(b[i])
    for i in g[0:5]:
      for b in range(len(a)):
        lst = []
        lst.append(a[b])
        i.append(lst)
    print(g)

However, my result is [[37100, [4]], [3710, [4]], [371, [4]], [37, [4]], [0, [4]]] Anyone knows how to solve it?

5 Answers

You can use itertools.zip_longest

from itertools import zip_longest
a = [1,2,3,4]
b = [37100,3710,371,37,0]

c = [1,2,3,4,5,6]
d = [1,2,3,4,5,6,7]

res = [[ii for ii in i if ii is not None] for i in zip_longest(b, a, c)]
print(res)

res = [[ii for ii in i if ii is not None] for i in zip_longest(b, a, c, d)]
print(res)

Output

[[37100, 1, 1], [3710, 2, 2], [371, 3, 3], [37, 4, 4], [0, 5], [6]]
[[37100, 1, 1, 1], [3710, 2, 2, 2], [371, 3, 3, 3], [37, 4, 4, 4], [0, 5, 5], [6, 6], [7]]

Edit based on comment:

from itertools import repeat
a = [1,2,3,4]
b = [371] * 100
c = [11,12,13,14]
d = [111,222,333,444]
res = [list(j) for i in zip(repeat(b), (a, c, d)) for j in zip(*i)]

print(res)

Here a solution that isn't data-dependant

a = [1, 2, 3, 4]
b = [37100, 3710, 371, 37, 0]
g = [[] for _ in range(max(len(a), len(b)))]
for i, sublist in enumerate(g):
    sublist.extend(b[i:i + 1])
    sublist.extend(a[i:i + 1])

Or with g unprepared

a = [1, 2, 3, 4]
b = [37100, 3710, 371, 37, 0]
g = []
for i in range(max(len(a), len(b))):
    g.append(b[i:i + 1] + a[i:i + 1])

Or itertools.zip_longest allows to pair data, and fill with a default value when one iterable is shorter, then you have to filter out that default value (None by default)

a = [1, 2, 3, 4]
b = [37100, 3710, 371, 37, 0]
g = [[val for val in pair if val is not None]
     for pair in zip_longest(b, a)]
# Assuming len(a) <= len(b)
g = []
for i in range(len(a)) :
  g.append([b[i], a[i]])
for i in range(len(a), len(b)) :
  g.append([b[i]])

Using map and lambda

a = [1,2,3,4]
b = [37100,3710,371,37,0]
map(lambda x, y: [x, y] if x is not None else [y], a, b)

Output

[[37100, 1], [3710, 2], [371, 3], [37, 4], [0]]

In the case of lengh a and b not equal

map(lambda x, y: [x, y] if x is not None and y is not None else ([y] if y is not None else [x]), a, b)
Related