Python列表添加删除计数

重复运算 *

将列表中的元素按顺序进行重复添加

list5 = [1,10,100] * 5
print(list5)

# 输出结果
[1, 10, 100, 1, 10, 100, 1, 10, 100, 1, 10, 100, 1, 10, 100]

成员运算(in / not in)

判断某个运算或者其他是否存在于列表中,返回的是布尔类型,存在就返回True,不存在就返回False.

print(10 in list5)
print(5 in list5)
print(10 not in list5)
print(5 not in list5)

# 输出结果
True
False
False
True

比较(并无意义)

两个列表进行比较其实是比较对应的字符编码。当符合条件之后就会停止,不管接下来还有多少,都不会在继续了。

list1 = [1, 3, 5, 7]
list2 = [4, 4, 8]
list3 = ['he']
list4 = ['hekio']
print(list1>list2)   # 1大于4
print(list3>list4)   # he两个都有,则比较之后的,明显list4大。
# 输出结果
False

列表的合并

两个列表进行合并时,将后者加入到前者的末尾,形成一个列表。

list1 = [1, 3, 5, 7]
list2 = [4, 4, 8]
# 列表的合并
temp = list1 + list2
list1.extend(list2)
print(list1)

# 输出结果
[1, 3, 5, 7, 4, 4, 8]

比较两列表对应元素相等

list1 = list(range(1, 8, 2))
list2 = [1, 3, 5, 7, 9]

print(list1 == list2)
print(list1 != list2)

# 输出结果
False
True

发现运算(index()

通过列表的内置方法找出元素是否存在于列表中,如果存在则返回索引,否则报错。

items = ['banana', 'grape', 'apple', '2', 'apple']
print(items.index('1'))  # 找出所给元素是否在列表中,在则输出第一次出现的索引,否则报错
print(items.index('apple', 3))  # 从索引为3开始找apple出现的第一次出现的索引

# 输出结果
# 不存在时候
ValueError: '1' is not in list

# 如果存在
4

返回的索引默认是第一次出现的索引位置。
可以指定从那个位置开始进行查找。

计数(count()

count()函数:对列表中给定的元素进行计数,统计出现的次数。

items = ['banana', 'grape', 'apple', '2', 'apple']
print(items.count('apple'))  # 统计元素在列表中出现的次数

# 输出结果
2

添加元素(append()insert()

append(): 在列表的末尾追加元素
insert():在指定的位置进行添加

# 添加元素
items.append('blueberry')
items.insert(1, 'watermelon')
print(items)

# 输出结果
['banana', 'watermelon', 'grape', 'apple', '2', 'apple', 'blueberry']

删除元素(pop()delremove()

items = ['banana', 'watermelon', 'grape', 'apple', '2', 'apple', 'blueberry']
 # 删除元素
items.pop()  # 删除末尾一个
items.pop(2)  # 删除指定位置索引元素
del items[0]   # 删除对应索引位置的元素
items.remove('apple')  # 删除第一次出现的元素
# 输出结果
['watermelon', '2', 'apple']

清空列表(clear())

items = [1,2,3]
items.clear()  # 清空列表之后,返回一个空列表
print(items)

# 输出结果
[]

删除列表(del)

items = [1,2,3]
del items    # 删除列表,再次输出列表时,会报错,没有该列表
print(items)

# 输出结果
NameError: name 'items' is not defined

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值