Python的列表(list)常规用法

1、创建列表


my_list = [1, 2, 3, 'apple', 'banana']

2、访问元素,索引从 0 开始


print(my_list[0])  # 输出: 1
print(my_list[3])  # 输出: apple

3、修改列表中的元素


my_list[1] = 'grape'
print(my_list)  # 输出: [1, 'grape', 3, 'apple', 'banana']

4、添加元素

4.1、 append: 在列表的末尾添加一个新元素


my_list.append('cherry')
print(my_list)  # 输出: [1, 'grape', 3, 'apple', 'banana', 'cherry']

4.2、 insert: 在指定位置插入一个新元素


my_list.insert(1, 'orange')
print(my_list)  # 输出: [1, 'orange', 'grape', 3, 'apple', 'banana', 'cherry']

4.3、 extend: 向列表添加另一个列表(或可迭代对象)的所有元素


new_list = [4, 6]
my_list.extend(new_list)
print(my_list)  # 输出: [1, 'orange', 'grape', 3, 'apple', 'banana', 'cherry', 4, 6]

5、使用 remove 删除第一个匹配的元素


my_list.remove('apple')
print(my_list)  # 输出: [1, 'orange', 'grape', 3, 'banana', 'cherry']

6、使用 pop 删除并返回指定位置的元素


popped_item = my_list.pop(2)
print(popped_item)  # 输出: grape
print(my_list)  # 输出: [1, 'orange', 3, 'banana', 'cherry']

7、使用 index 查找第一个匹配的元素的索引


print(my_list.index('cherry'))  # 输出: 4

8、使用 count 计算指定元素出现次数


print(my_list.count(1))  # 输出: 1

9、使用 sort 对列表进行排序


numbers = [5, 1, 9, 3, 7]
numbers.sort()
print(numbers)  # 输出: [1, 3, 5, 7, 9]

10、使用 reverse 颠倒列表元素的顺序


numbers.reverse()
print(numbers)  # 输出: [9, 7, 5, 3, 1]

11、使用 copy 复制一个列表


new_list = my_list.copy()
print(new_list)  # 输出: [1, 'orange', 3, 'banana', 'cherry']

12、列表推导式


new_list = [ str(my_data) + '_' for my_data in my_list]

13、判断某个值 是否在列表中


lists = [[1, 2], [3, 4], [5, 6]]

if [1, 2] in lists:
    print("[1, 2] is in the list")
else:
    print("[1, 2] is not in the list")

if [7, 8] in lists:
    print("[7, 8] is in the list")
else:
    print("[7, 8] is not in the list")


class Person:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return self.name == other.name

persons = [Person("Alice"), Person("Bob"), Person("Charlie")]

if Person("Alice") in persons:
    print("Person named Alice is in the list")
else:
    print("Person named Alice is not in the list")

if Person("David") in persons:
    print("Person named David is in the list")
else:
    print("Person named David is not in the list")

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值