标签:range 构建 通过 pop 创建 code [] for remove
python中用 [ ] 来表示列表,列表中各元素以 , 分隔开,如
fruits = [‘apple‘, ‘orange‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
print (fruits)
# result
[‘apple‘, ‘orange‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
访问列表中的元素:
1 # 列表中元素以0开始,若显示orange,则:
2 print (fruits[1])
# -1为列表的最后一个元素
print(fruits[-1])
# result
watermelon
修改列表中的元素
fruits[1] = peach
print (fruits)
# result
[‘apple‘, ‘peach‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
列表末尾添加元素:
fruits.append(‘peach‘)
print(fruits)
# result
[apple, banana, pear, watermelon, peach]
构建fruits列表
fruits = []
fruits.append(‘apple‘)
fruits.append(‘banana‘)
fruits.append(‘pear‘)
fruits.append(‘watermelon‘)
print(fruits)
# result
[‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
在列表中插入元素
fruits.insert(1, peach)
print(fruits)
# result
[‘apple‘, ‘peach‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
删除列表中的元素
# del
del fruits[1]
print (fruits)
# result
[‘apple‘, ‘pear‘, ‘watermelon‘]
# pop()
apple = fruits.pop(0)
print (apple)
print (fruits)
# result
apple
[‘banana‘, ‘pear‘, ‘‘watermelon‘]
# remove()
fruits.remove(‘pear‘)
print(fruits)
# result
[‘apple‘, ‘banana‘, ‘watermelon‘]
列表排序
# 永久排序
fruits.sort()
print (fruits)
# result
[‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
# 倒序
fruits.sort(reverse=True)
print(fruits)
[‘watermelon‘, ‘pear‘, ‘banana‘, ‘apple‘]
# 临时排序
print(fruits)
print(sorted(fruits))
print(fruits)
# result 假设原fruits为[ ‘banana‘, ‘apple‘, ‘pear‘, ‘watermelon‘]
[ ‘banana‘, ‘apple‘, ‘pear‘, ‘watermelon‘]
[‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
[ ‘banana‘, ‘apple‘, ‘pear‘, ‘watermelon‘]
列表倒序
fruits.reverse()
print(fruits)
# result
[‘watermelon‘, ‘pear‘, ‘banana‘, ‘apple‘]
获取列表长度
print(len(fruits))
# result
4
列表遍历:
for fruit in fruits:
print(fruit)
# result
apple
banana
peer
watermelon
函数range
for value in range(1, 5):
print (value)
# result 不包含末尾值
1
2
3
4
# 使用range创建数字列表
values = list(range(1, 6))
print (values)
# result
[1, 2, 3, 4, 5]
# 打印偶数
values = list(range(2, 11, 2))
print (values)
# result
[2, 4, 6, 8, 10]
# 数字统计计算
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(min(values))
print(max(values))
print(sum(value))
列表切片
print(fruits[0:3])
# result 左闭右开
[‘apple‘, ‘banana‘, ‘pear‘]
print(fruits[:3])
# result 左侧无起始值,则默认从开头位置取,若右侧无终止值,则一直取到list的末尾
[‘apple‘, ‘banana‘, ‘pear‘]
切片遍历
for fruit in fruits[0:3]
print (fruit)
# result
[‘apple‘, ‘banana‘, ‘pear‘]
通过切片复制列表
my_fruits = fruits[:]
print (my_fruits)
# result
[‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
标签:range 构建 通过 pop 创建 code [] for remove
原文地址:https://www.cnblogs.com/zhangshuang0909/p/9535558.html