欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python用range构建list

程序员文章站 2022-05-04 16:54:31
...

首先这样是行不通的

# Create a list in a range of 10-20
My_list = [range(10, 20, 1)]

# Print the list
print(My_list)

正确的方法是使用*代表unpackage

# Create a list in a range of 10-20
My_list = [*range(10, 21, 1)]

# Print the list
print(My_list)

或者extend

# Create an empty list
My_list = []

# Value to begin and end with
start, end = 10, 20

# Check if start value is smaller than end value
if start < end:
	# unpack the result
	My_list.extend(range(start, end))
	# Append the last value
	My_list.append(end)

# Print the list
print(My_list)