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

孤街醉人 提交于 2019-12-30 05:24:07

问题


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'


回答1:


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.




回答2:


To get a list of lists, you can use the built-in function zip() and list comprehension to convert each element of the result of zip() from a tupleto a list:

A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]

X = [list(e) for e in zip(A, B, C,)]

print X
>>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]



回答3:


Assuming you are doing this for class and not learning all of the tricks that make Python a great tool here is what you need. You had two problems, first if you want to extend then you do it in place but your desired result shows that you want to append, not extend

def 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.append(temp)
   return answer


>>> answer
[[1, 'a', 'x'], [2, 'b', 'y'], [3, 'c', 'z']]


来源:https://stackoverflow.com/questions/22597966/is-there-a-way-to-merge-multiple-list-index-by-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!