在python中混合列表

时间:2015-11-25 15:37:44

标签: python list

from itertools import product

x_coord = ['a','b','c','d','e']
y_coord = ['1', '2', '3', '4', '5']

board = []
index = 0

for item in itertools.product(x_coord, y_coord): 

    board += item

    for elements in board:

        board[index] = board[index] + board[index +1]
        board.remove(board[index +1])
        index += 1


print board

您好。让我解释一下我想用它做什么:

我有两个列表(x_coordy_coord),我希望将它们混合起来:

board = ['a1', 'a2', ..., 'e1', 'e2', ...]

但是我得到IndexError: list index out of range错误而不是。

我该怎么办?

OBS.:如果我的英文中有任何类型的错误,请告诉我。我正在学习英语和代码。

5 个答案:

答案 0 :(得分:2)

你可以这样试试,

>>> x_coord = ['a','b','c','d','e']
>>> y_coord = ['1', '2', '3', '4', '5']
>>> [item + item2 for item2 in y_coord for item in x_coord]
['a1', 'b1', 'c1', 'd1', 'e1', 'a2', 'b2', 'c2', 'd2', 'e2', 'a3', 'b3', 'c3', 'd3', 'e3', 'a4', 'b4', 'c4', 'd4', 'e4', 'a5', 'b5', 'c5', 'd5', 'e5']

排序结果:

 >>> sorted([item + item2 for item2 in y_coord for item in x_coord])
['a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4', 'b5', 'c1', 'c2', 'c3', 'c4', 'c5', 'd1', 'd2', 'd3', 'd4', 'd5', 'e1', 'e2', 'e3', 'e4', 'e5']

答案 1 :(得分:0)

t = [a + b for a,b in itertools.product(x_coord,y_coord)]
print t % prints what you want

通常itertools.product(x_coord,y_coord)会打印以下内容: [('a','1'),('a','2'),('a','3'),('a','4'),('a','5') ,('b','1'),('b','2'),('b','3'),('b','4'),('b','5') ,('c','1'),('c','2'),('c','3'),('c','4'),('c','5') ,('d','1'),('d','2'),('d','3'),('d','4'),('d','5') ,('e','1'),('e','2'),('e','3'),('e','4'),('e','5') ]

正如您所看到的那样,因为itertools.product会将a乘以y_coord中的每个索引,然后再将x_coord移动到b等等。

通过使用list comprehension,我们可以使用a+b为输出中的每一对组合两个索引,从而产生以下结果:
['a1','a2','a3','a4','a5','b1','b2','b3','b4','b5','c1','c2',' c3','c4','c5','d1','d2','d3','d4','d5','e1','e2','e3','e4','e5' ]

答案 2 :(得分:0)

combined = map(lambda x: ''.join(x), product(x_coord, y_coord))

答案 3 :(得分:0)

coord = map(lambda x,y: x+y, x_coord, y_coord)   
print(coord)  

答案 4 :(得分:-1)

x_coord = ['a','b','c','d','e']
y_coord = ['1', '2', '3', '4', '5']
a=[]
for i in range(len(x_coord)):
    for j in range(len(y_coord)):
        a.append(x_coord[i].join(" "+ y_coord[j]))
b=[]
for item in a:
    b.append(item.replace(" ",""))
print b
相关问题