Python基础知识-列表常见操作

1、sort函数,列表元素的排序,默认增序排序

fruit = ['banana', 'pear', 'apple', 'peach']
print(fruit)
fruit_1 = fruit.copy()#复制新列表
print(fruit_1)
fruit_1.sort()#增序排序
print(fruit_1)
fruit_1.sort(reverse = True)#逆序排序
print(fruit_1)

['banana', 'pear', 'apple', 'peach']#原列表
['banana', 'pear', 'apple', 'peach']#拷贝
['apple', 'banana', 'peach', 'pear']#增序排序
['pear', 'peach', 'banana', 'apple']#逆序排序

由以上可知,列表排的是ASCII码,首字母相同的情况下依次往后比较。

2、copy函数,列表元素的复制

#列表复制
vegetable = ['白菜','萝卜','青菜','芹菜','花菜','白菜']
print(vegetable)
print(id(vegetable))
new_vege = vegetable.copy()
print(id(new_vege))#copy之后生成的新列表的地址不同

 打印输出:

['白菜', '萝卜', '青菜', '芹菜', '花菜', '白菜']
3032979076296
3032978997832

由此可见copy后的新列表仅仅是元素相同,但其地址不同。

直接幅值的方式生成的新列表,其地址是相同的

#列表复制
vegetable = ['白菜','萝卜','青菜','芹菜','花菜','白菜']
print(vegetable)
print(id(vegetable))
new_vege = vegetable.copy()
print(id(new_vege))#copy之后生成的新列表的地址不同
new_list = vegetable
print(id(new_list))

打印输出

['白菜', '萝卜', '青菜', '芹菜', '花菜', '白菜']
2620476683528
2620476605128
2620476683528

3、列表元素的统计

vegetable = ['白菜','萝卜','青菜','芹菜','花菜','白菜']
print(vegetable.count('白菜'))
print(vegetable.count('萝卜'))

 打印

2
1

4、列表元素的反向记录

#列表元素的反向记录
vegetable = ['白菜','萝卜','青菜','芹菜','花菜','白菜']
print(vegetable)
vegetable.reverse()
print(vegetable)

['白菜', '萝卜', '青菜', '芹菜', '花菜', '白菜']
['白菜', '花菜', '芹菜', '青菜', '萝卜', '白菜']

5、列表解析

 对集合0~10,除0之外求平方

只需一行元素

Nums = [i**2 for i in range(11) if i >0]
print(Nums)

 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

上述代码具有简洁的优点,但是有些转接不推荐使用该方法,因为:

(1)在计算过程中容易发生错误,调试不方便;

(2)该风格的代码比较另类,不常见。

我们可以用一般的方法。

Nums = []
for i in range(1,11):
    Nums.append(i**2)
print(Nums)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

6、列表长度

first_record = [18, 8, 7, 2, 3, 6, 1, 1]
print(first_record)
Len = len(first_record)#列表长度
print(Len)

输出列表的长度:8

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nwsuaf_huasir

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值