Py学习  »  Python

将python for循环转换为一行代码

cget • 6 年前 • 2000 次点击  

如何将此for循环转换为一行代码?

numbers = []
for i in range(51):
    numbers.append(i)

print(numbers)

预期输出是包含1到50([1…50])的数字列表

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52780
文章 [ 4 ]  |  最新文章 6 年前
nucsit026
Reply   •   1 楼
nucsit026    6 年前

您可以使用:

print(list(range(1,51)))

或:

print([i for i in range(1,51)])
TJC World
Reply   •   2 楼
TJC World    6 年前

分号有时很有用:

>>> numbers = list(range(51)); print(numbers)

输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
abc
Reply   •   3 楼
abc    6 年前

范围可以直接转换为列表

numbers = list(range(1,51))
zamir
Reply   •   4 楼
zamir    6 年前

使用列表理解:

numbers = [i for i in range(51)]