小甲鱼-010-012列表

python列表可以没有类型限制,可以存放不同类型的数据,如整型、浮点型、字符串、对象、列表、tuple

1.创建列表

#普通列表
autos = ['一汽', '东风','上汽','长安', '广汽']
#混合列表
mix_autos = [1, '大雄', ['机器猫','小夫'],(1,3),{'龙珠':'比克','铁甲小宝':'卡布达'}]
#空列表
empty = []

1418970-20181231233430852-848343340.png

2.添加元素

append追加,extend添加一个列表,insert指定位置添加

empty = ['蛇精', '蝎子精', '穿山甲', '青蛙','瓢虫']
#追加
empty.append('葫芦娃')
#追加个列表
empty.extend(['大娃','二娃'])
#指定位置添加
empty.insert(1, '爷爷')
print(empty)

1418970-20181231234118403-142976151.png

3.删除元素

remove pop del

empty = ['大娃', '二娃', '三娃', '四娃','五娃', '六娃', '七娃']
#根据列表的值删除
empty.remove('七娃')
#pop默认删除最后一个,也可指定索引
a = empty.pop()
empty.pop(4)
#根据索引删除列表的值
del empty[0]
print(empty)
#删除整个列表
del empty

1418970-20181231234732491-2032198426.png

4.切片

empty = ['大娃', '二娃', '三娃', '四娃','五娃', '六娃', '七娃']

#切片选取部分列表,可以指定初始位置和结束位置,不指定就选取整个列表
list1 = empty[1:3]
list2 = empty[:5]
list3 = empty[3:]
list4 = empty[:]
print(list1)
print(list2)
print(list3)
print(list4)

1418970-20181231235401176-1847430165.png

5.常用操作符

5.1比较操作符 > < ==

list1 = [123,456]
list2 = [234,567]
list3 = [123,567]
print(list1 < list2)
print(list1 < list3)
print(list1 == list2)
print(list1 == list3)

1418970-20190101093239465-181712328.png

5.2逻辑操作符 and or not

list1 = [123,456]
list2 = [234,567]
list3 = [123,567]
print((list1 < list2) and (list1 < list3))
print((list1 == list2) or (list1 < list3))
print(not (len(list2) > 3))

1418970-20190101093808649-1009843537.png

5.3连接操作符 +

list1 = [123,456]
list2 = [234,567]
list3 = list1 + list2
print(list3)
1418970-20190101101755805-1749927943.png

5.4重复操作符 *

list1 = [123,456]
list3 = list1 * 3
list1 *= 2
print(list1)
print(list3)

1418970-20190101101952696-359444186.png

5.5成员关系操作符 in

empty = ['大娃', '二娃', '三娃', '四娃','五娃', '六娃', '七娃']
print('大娃' in empty)
print('蛇精' not in empty)
mix_autos = [1, '大雄', ['机器猫','小夫']]
print('机器猫' in mix_autos[2])

1418970-20190101103742990-1746066510.png

6.列表的内置方法

len列表长度
count查看值在列表中出现的次数
index返回值在列表中的索引
reverse 反序
sort(reverse=False)

empty = [9,7,13,85,3,67]
empty *= 2
print(empty)
print(empty.count(9))
print(empty.index(7))
print(empty.index(13,3,9))
#排序
empty.sort()
#反向排序
empty.sort(reverse=True)
print(empty)
#反向
empty.reverse()
print(empty)

1418970-20190101105604972-147649953.png?

FAQ

复制列表要使用切片,因为直接复制列表并不会生成新列表,依旧指向旧列表。针对列表的所有操作都会被记录

转载于:https://www.cnblogs.com/csj2018/p/10095129.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值