鱼C论坛

 找回密码
 立即注册
查看: 1903|回复: 0

[技术交流] 《零基础学习Python》12列表 一个打了激素的数组3

[复制链接]
发表于 2017-7-19 21:51:26 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 只为 于 2017-8-29 21:50 编辑

1、列表的一些常用操作符
1)比较操作符
  1. >>>list1=[123,456]
  2. >>>list2=[234,123]
  3. >>>list1>list2
  4. False
复制代码

注意:list比较的话,当有多个元素的时候,默认是从第0个元素开始比较的,只有第0个元素list1小,整个列表都小,不用考虑后边的元素。跟字符串的比较一样,比较ASCII码的大小
  1. >>> list1 = [123,456]
  2. >>> list3 = ['a']
  3. >>> list1>list3
  4. Traceback (most recent call last):
  5.   File "<pyshell#5>", line 1, in <module>
  6.     list1>list3
  7. TypeError: unorderable types: int() > str()

  8. >>> list3 = ['a']
  9. >>> list5 = [True]
  10. >>> list3 > list5
  11. Traceback (most recent call last):
  12.   File "<pyshell#11>", line 1, in <module>
  13.     list3 > list5
  14. TypeError: unorderable types: str() > bool()

  15. >>> list5 = [True]
  16. >>> list6=[None]
  17. >>> list5>list6
  18. Traceback (most recent call last):
  19.   File "<pyshell#17>", line 1, in <module>
  20.     list5>list6
  21. TypeError: unorderable types: bool() > NoneType()
复制代码

note:经多次试验,只有当列表中的首元素数据类型相同时,才能进行算术运算操作

2)逻辑操作符
  1. >>> list1 = [123,456]
  2. >>> list2=[234]
  3. >>> list3 = [123,456]
  4. >>> (list1<list2) and (list1==list3)
  5. True
复制代码


3)连接操作符  +
注意:有些事违规的,不能添加新元素,+ 连接符两边的数据类型必须一致的
  1. >>> list1 = [123,456]
  2. >>> list1  + '小甲鱼'
  3. Traceback (most recent call last):
  4.   File "<pyshell#1>", line 1, in <module>
  5.     list1  + '小甲鱼'
  6. TypeError: can only concatenate list (not "str") to list
  7. >>>
复制代码

建议:列表之间不要使用连接操作符,使用extend()方法

4)重复操作符  *
  1. >>> list3 = [123,456]
  2. >>> list3*3
  3. [123, 456, 123, 456, 123, 456]
  4. >>> list3
  5. [123, 456]
  6. >>> list3 *=3
  7. >>> list3
  8. [123, 456, 123, 456, 123, 456]
复制代码


5)成员关系操作符  in ,not in
  1. >>> list1=[123,['小甲鱼','二货'],True,None]
  2. >>> 123 in list1
  3. False
  4. >>> '小甲鱼' in list1
  5. False
  6. >>> '小甲鱼' in list[1]
  7. True
  8. >>> lis1t[1][1]
  9. '二货'
复制代码


2、列表的小伙伴们(官方:列表类型的内置函数)
  1. dir(list)
复制代码


属于列表(某一个对象)的内置函数,用点记法使用。
1)count(list)--->int
2)index()--->int   index(元素,start, end)
常用的:
3)reverse()--->list        反转
4)sort()--->list 默认从小到大排序
list.sort(func,key,reverse=False)  前两个参数是默认的,可以不写的,reverse默认是False
list.sort(reverse=True) 相当于先sort()排序,在reverse()反转的效果

关于分片‘拷贝’补充:
  1. >>> list3=[9,8,7,4,2,0]
  2. >>> list4 = list3[:]
  3. >>> list4
  4. [9, 8, 7, 4, 2, 0]
  5. >>> list5=list3
  6. >>> list5
  7. [9, 8, 7, 4, 2, 0]
  8. >>> list3.sort()
  9. >>> list3
  10. [0, 2, 4, 7, 8, 9]
  11. >>> list4
  12. [9, 8, 7, 4, 2, 0]
  13. >>> list5
  14. [0, 2, 4, 7, 8, 9]
复制代码

注意:如果需要拷贝,使用分片的形式

评分

参与人数 1鱼币 +3 收起 理由
小甲鱼 + 3

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-10 21:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表