python列表操作
2021-07-15 22:06
标签:range 构建 通过 pop 创建 code [] for remove python中用 [ ] 来表示列表,列表中各元素以 , 分隔开,如 # result 访问列表中的元素: 修改列表中的元素 列表末尾添加元素: 构建fruits列表 在列表中插入元素 删除列表中的元素 列表排序 列表倒序 获取列表长度 列表遍历: 函数range 列表切片 print(fruits[:3]) 切片遍历 通过切片复制列表 python列表操作 标签:range 构建 通过 pop 创建 code [] for remove 原文地址:https://www.cnblogs.com/zhangshuang0909/p/9535558.htmlfruits = [‘apple‘, ‘orange‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
print (fruits)[‘apple‘, ‘orange‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
1 # 列表中元素以0开始,若显示orange,则:
2 print (fruits[1])
# -1为列表的最后一个元素
print(fruits[-1])
# result
watermelonfruits[1] = peach
print (fruits)
# result
[‘apple‘, ‘peach‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
fruits.append(‘peach‘)
print(fruits)
# result
[apple, banana, pear, watermelon, peach]
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
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‘]
# 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‘]