Python_list用法

本文详细介绍了Python列表中的11种常见方法,包括append、clear、copy、count、extend、index、insert、pop、remove、reverse和sort,每个方法都配以实例演示和功能解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# list类型中所有的方法(除sort之外), 每一个方法附带一个实例:以及解释说明
#1. help(list.append)追加
# append(self, object, /)
#     Append object to the end of the list.将对象追加到列表的末尾。
data_1 = [1, 1.1, True, 1 + 2j, 'hello', None, (1, 2), []]
data_1.append(99)
print(data_1)
#2. help(list.clear)清除
# clear(self, /)
#     Remove all items from list.从列表中删除所有项目。
data_2 = [1, 1.1, True, 1 + 2j, 'hello', None, (1, 2), []]
data_2.clear()
print(data_2)
#3. help(list.copy)复制
# copy(self, /)
#     Return a shallow copy of the list.返回列表的浅拷贝。
data_3 = [1, 1.1, True, 1 + 2j, 'hello', None, (1, 2), []]
print(data_3.copy())
#4. help(list.count)计数
# count(self, value, /)
#     Return number of occurrences of value.返回value出现的次数。
data_4 = [1, 1.1, True, 1 + 2j, 'hello', None, (1, 2), [], []]
print(data_4.count([]))
#5. help(list.extend)
# extend(self, iterable,(可迭代) /)扩展
#     Extend list by appending elements from the iterable.通过从可迭代对象中添加元素来扩展列表。
data_5_a = [1, 1.1, True, 1 + 2j, 'hello', None, (1, 2), [], []]
data_5_b = [1, 1.1, True, 1 + 2j, 'hello', None, (1, 2), [], []]
print(data_5_a.extend(data_5_b))
print(data_5_a)
#6. help(list.index)索引
# index(self, value, start=0, stop=9223372036854775807, /)
#     Return first index of value.返回值的第一个索引。
data_6 = [1, 1.1, True, [],  1 + 2j, 'hello', None, (1, 2), [], []]
print(data_6.index([]))
print(data_6.index([], 5))
#7. help(list.insert)
# insert(self, index, object, /)插入
#     Insert object before index.在索引之前插入对象。
data_7 = [1, 1.1, True, [],  1 + 2j, 'hello', None, (1, 2), [], []]
data_7.insert(3, 'abc')
print(data_7)
#8. help(list.pop)
# pop(self, index=-1, /)
#     Remove and return item at index (default last).删除并返回索引处的项(默认最后)。
data_8 = [1, 1.1, True, [],  1 + 2j, 'hello', None, (1, 2), [], []]
print(data_8.pop(4))
print(data_8)
#9. help(list.remove)删除
# remove(self, value, /)
#     Remove first occurrence of value.删除value的第一次出现。
data_9 = [1, 1.1, True, [],  1 + 2j, 'hello', None, (1, 2), [], []]
print(data_9.remove([]))
print(data_9)
#10. help(list.reverse)反向
# reverse(self, /)
#     Reverse *IN PLACE*.反向*到位*。
data_10 = [1, 1.1, True, [],  1 + 2j, 'hello', None, (1, 2), [], []]
print(data_10.reverse())
print(data_10)
#11. help(list.sort)排序
# sort(self, /, *, key=None, reverse=False)
#     Sort the list in ascending order and return None.对列表按升序排序并返回None。
data_11 = [1, 3, 7, 9]
#降序
print(data_11.sort(reverse=True))
print(data_11)
#升序
print(data_11.sort(reverse=False))
print(data_11)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值