简体   繁体   English

创建一个从一号到第n号Python的数字列表

[英]Creating a list of numbers one through nth Python

How can I create a list one through nth that gives me a list, that is only one digit in length. 我如何才能创建一个列表到第n个列表,该列表只有一个数字。 So 100 would be 1,0,0 and 19 would be 1,9 所以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]
def listgen(n):
    return map(int, ''.join(map(str, range(1, n + 1))))

Breaking it apart: 分解:

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]

The above code is written for python 2. For python 3 you could convert the map to list . 上面的代码是针对python 2编写的。对于python 3,您可以将map转换为list

Or, without map()... 或者,没有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] [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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM