如何创建一个到第n个列表,它给出了一个列表,即长度只有一位数。所以100将是1,0,0而19将是1,9
>>> listGen(20)
>>> [1,2,3,4,5,6,7,8,9,1,0,1,1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,2,0]
答案 0 :(得分:3)
def listgen(n):
return map(int, ''.join(map(str, range(1, n + 1))))
将其分开:
n = 10
a = range(1, n + 1) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = map(str, a) # ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
c = ''.join(b) # '12345678910'
d = map(int, c) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0]
上面的代码是为python 2编写的。对于python 3,你可以将map
转换为list
。
答案 1 :(得分:1)
或者,没有map()......
>>> [int(c) for c in ''.join([str(n) for n in range(1,21)])]
[1,2,3,4,5,6,7,8,9,1,0,1,1,1,2,1,3,1,4,1,5,1,6, 1,7,1,8,1,9,2,0]