列表
按特定顺序排列的元素列成
取复数名字比较好: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