Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to merge multiple list index by index?

For example, I have three lists (of the same length)

A = [1,2,3]
B = [a,b,c]
C = [x,y,z]

and i want to merge it into something like: [[1,a,x],[2,b,y],[3,c,z]].

Here is what I have so far:

define merger(A,B,C):
  answer = 
  for y in range (len(A)):
    a = A[y]
    b = B[y]
    c = C[y]
    temp = [a,b,c]
    answer = answer.extend(temp)
  return answer

Received error:

'NoneType' object has no attribute 'extend'

like image 653
user3225528 Avatar asked Dec 12 '22 06:12

user3225528


1 Answers

It looks like your code is meant to say answer = [], and leaving that out will cause problems. But the major problem you have is this:

answer = answer.extend(temp)

extend modifies answer and returns None. Leave this as just answer.extend(temp) and it will work. You likely also want to use the append method rather than extend - append puts one object (the list temp) at the end of answer, while extend appends each item of temp individually, ultimately giving the flattened version of what you're after: [1, 'a', 'x', 2, 'b', 'y', 3, 'c', 'z'].

But, rather than reinventing the wheel, this is exactly what the builtin zip is for:

>>> A = [1,2,3]
>>> B = ['a', 'b', 'c']
>>> C = ['x', 'y', 'z']
>>> list(zip(A, B, C))
[(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]

Note that in Python 2, zip returns a list of tuples; in Python 3, it returns a lazy iterator (ie, it builds the tuples as they're requested, rather than precomputing them). If you want the Python 2 behaviour in Python 3, you pass it through list as I've done above. If you want the Python 3 behaviour in Python 2, use the function izip from itertools.

like image 198
lvc Avatar answered Jan 01 '23 08:01

lvc