python基础学习(五):列表

1.创建

空列表

>>> test=[]
>>> test
[]


非空

数据类型可以不同

>>> member=[1,1,2,'hello']

>>> member
[1, 1, 2, 'hello']


2.添加元素

(1).方法append()

可以在尾部追加一个元素

>>> test=['lucy','tom','bob']
>>> test.append('mary')
>>> test
['lucy', 'tom', 'bob', 'mary']

(2).方法extend()

可以用一个列表扩展另一个列表,参数为一个列表

>>> test.extend(['kaka','messi'])
>>> test
['lucy', 'tom', 'bob', 'mary', 'kaka', 'messi']

(3)方法insert()

可以在任意位置添加位置

>>> test.insert(0,'c罗')
>>> test
['c罗', 'lucy', 'tom', 'bob', 'mary', 'kaka', 'messi']


3.从列表获取一个元素

以上例test为例,可以test[i],i=0,1,2...


4.从列表删除一个元素

(1)成员方法remove(元素名字)

>>> haha=[1,2,3]
>>> haha.remove(3)
>>> haha
[1, 2]

(2)del函数

>>> haha=[1,2,3,4]
>>> del haha[1]
>>> haha
[1, 3, 4]
>>> del haha
>>> haha
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    haha
NameError: name 'haha' is not defined

可以删除某个元素,也可删除整个列表,将之从内存踢掉

(3)成员方法pop()

>>> test
['c罗', 'tom', 'bob', 'mary', 'kaka']
>>> test.pop()
'kaka'
>>> test.pop(0)
'c罗'


可以不加参数坡派出最后一个元素,也可以参数加索引,返回值为被pop出的元素值。


5.从列表中获取多个元素

列表分片(slice)

>>> test[0:2]
['tom', 'bob']

参数为起止索引,两个参数都可省略(元素不包括2对应的元素)
>>> test[:2]
['tom', 'bob']
>>> test[1:]
['bob', 'mary']
>>> test2=test
>>> test2
['tom', 'bob', 'mary']
>>> test2=test[:]
>>> test2
['tom', 'bob', 'mary']


6.列表一些常用操作

(1)比较操作符

>>> list1=[123,234,345]
>>> list2=[456,567]
>>> list1>list2
False

>>> list3=[345,123]
>>> list4=[345,234]
>>> list3<list4
True

>>> haha1=['tina','bob']
>>> haha2=['jim','lucy']
>>> haha1<haha2
False
>>> haha1>haha2
True

比较时,依次从第一个元素开始比较,一旦能比较出结果就停止。

(2)逻辑操作符

>>> list1<list2 and list3<list4
True


(3)连接操作符

可用+拼接两个列表

>>> list1=[123,234]

>>> list2=[456,567]
>>> list1+list2
[123, 234, 456, 567]

加号两端数据类型需一致,所以下面程序报错

>>> list1+456
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    list1+456
TypeError: can only concatenate list (not "int") to list
>>> list1+"678"
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    list1+"678"
TypeError: can only concatenate list (not "str") to list

(4)重复操作符

用*号

>>> list1*3
[123, 234, 123, 234, 123, 234]

重复操作符也可用于赋值

>>> list1*=4
>>> list1
[123, 234, 345, 123, 234, 345, 123, 234, 345, 123, 234, 345]

(5)成员关系操作符

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值