是否有更多pythonic方式生成以下列表?

时间:2017-07-19 23:28:04

标签: python python-3.x

列表:

['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 
 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7',
 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7',
 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7',
 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7',
 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7',
 'g0', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7',
 'h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7']

我尝试过使用itertools但没有成功,

我目前生成以上列表的代码是:

dmi_list = []
for i in range(ord('a'), ord('i')):
  for j in range(0,8):
     dmi_list.append(chr(i)+str(j))

print(dmi_list)

3 个答案:

答案 0 :(得分:3)

简单列表理解将是我的选择:

>>> [x + y for x in 'abcdefgh' for y in '01234567']
['a0',
 'a1',
 'a2',
 'a3',
 ...
 'h7']

答案 1 :(得分:2)

确实有。您可以使用itertools.product

import itertools
l = [''.join(k) for k in itertools.product('abcdefgh', '01234567')]

print(l)

打印:

['a0',
 'a1',
 'a2',
 'a3',
 'a4',
 'a5',
 'a6',
 'a7',
 ...
 'h4',
 'h5',
 'h6',
 'h7']

如果嵌套列表comp只是产品b / w 2列表,那么它就没问题了。更多信息,您可能会发现自己想要使用此功能。

答案 2 :(得分:0)

我只想写

 [letter + number for letter in 'abcdefgh' for number in '01234567']
相关问题