python书(2)列表简介

列表
按特定顺序排列的元素列成
取复数名字比较好:letters,names
[ ]元素,隔开,索引从0开始,倒过来从-1开始
这里只能用双引号
在这里插入图片描述
names=[‘lili’,‘hjhj’,‘JKJK’,‘HNHN’]
print(names[0])
print(names[1])
print(names[2])
print(names[3])
message='hello, '+names[1]
message='hello, '+names[2]
message='hello, '+names[3]
message='hello, '+names[0]
commutes=[‘bike’,‘bus’,‘motorcyle’]
xuanyan="I would like to own a "+commutes[0]
print(xuanyan)
显示
lili
hjhj
JKJK
HNHN
I would like to own a bike
修改,添加,删除元素

修改在这里插入图片描述
显示
[‘Honda’, ‘yamaha’, ‘suzuzi’]
[‘ducati’, ‘yamaha’, ‘suzuzi’]

添加元素append(’’)
在这里插入图片描述插入insert()
在这里插入图片描述
删除元素de’l,不再使用
在这里插入图片描述
弹出pop可以任何指定,弹出还能用在这里插入图片描述
pop弹出指定
在这里插入图片描述
remove根据值删除

>>> a=['he','df','hj']
>>> print(a)
['he', 'df', 'hj']
>>> a.remove('df')
>>> print(a)
['he', 'hj']

排序大法
sort

a=['ghj','bhjmm','fdds','thbb']
>>> a.sort()
>>> a
['bhjmm', 'fdds', 'ghj', 'thbb']
>>> a.sort(reverse=True)
>>> a
['thbb', 'ghj', 'fdds', 'bhjmm']

sorted临时调顺序


>>> a=['ghj','bhjmm','fdds','thbb']
>>> a.sort()
>>> a
['bhjmm', 'fdds', 'ghj', 'thbb']
>>> a.sort(reverse=True)
>>> a
['thbb', 'ghj', 'fdds', 'bhjmm']
>>> print("here is the original list:")
here is the original list:
>>> print(a)
['thbb', 'ghj', 'fdds', 'bhjmm']
>>> print("\nhere is the sorted list:")

here is the sorted list:
>>> print(sorted(a))
['bhjmm', 'fdds', 'ghj', 'thbb']
>>> print("\nhere is the original list again:")

here is the original list again:
>>> print(a)
['thbb', 'ghj', 'fdds', 'bhjmm']

翻转列表
reverse()
输2次又恢复

a=['ghj','bhjmm','fdds','thbb']
>>> print(a)
['ghj', 'bhjmm', 'fdds', 'thbb']
a=['ghj','bhjmm','fdds','thbb']
>>> print(a)
['ghj', 'bhjmm', 'fdds', 'thbb']

练习题

>>> place=['aaa','sss','aaw','asx','wss']
>>> print(place)
['aaa', 'sss', 'aaw', 'asx', 'wss']
`>>> print(sorted(place))
['aaa', 'aaw', 'asx', 'sss', 'wss']
>>> print(place)
['aaa', 'sss', 'aaw', 'asx', 'wss']
>>> place.reverse()
>>> print(place)
['wss', 'asx', 'aaw', 'sss', 'aaa']
>>> place.reverse()
>>> print(place)
['aaa', 'sss', 'aaw', 'asx', 'wss']
>>> place.sort()
>>>> print(place)
['aaa', 'aaw', 'asx', 'sss', 'wss']
>>> place.sort(reverse=True)
>>> print(place)
['wss', 'sss', 'asx', 'aaw', 'aaa']``

``
len()长度
注意索引错误,从0开始

>>> a=['ghj','bhjmm','fdds','thbb']
>>> len(a)
4
>>> print(a[4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> print(a[3])
thbb
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值