使用range()创建数字列表
numbers = list(range(1,6))
print(numbers)
结果:
[1, 2, 3, 4, 5]
Process finished with exit code 0
#指定步长
even_numbers = list(range(2,11,2))
print(even_numbers)
结果:
[2, 4, 6, 8, 10]
Process finished with exit code 0
#简单的统计
digits = [1,2,3,4,5]
print(min(digits))
print(max(digits))
print(sum(digits))
结果:
1
5
15
Process finished with exit code 0
列表解析
n行 合成 1行
阅读他人代码时经常遇到类似的
squares = [value**2 for value in range(1,11)]
print(squares)
结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Process finished with exit code 0
使用列表的一部分
切片
players = ['a','b','c','d']
print(players[0:3])
结果:
['a','b','c']
players[:4] //从头开始
players[2:] //从第三个元素到末尾
players[-3:] //输出后三个元素
利用切片复制列表
#相当于两个列表
players = ['a','b','c','d']
players_1 = players[:]
#下面就是单纯的赋值,使用的是同一个列表
players = ['a','b','c','d']
players_2 = players