Python 列表、元组
1. 列表的合并
a=[]
a.append('liudaoheng')
print(a)
b=['liuchen']
a.extend(b)
print(a)
['liudaoheng']
['liudaoheng', 'liuchen']
2. 列表的添加
b=['liuchen']
b.insert(1,'lindongli') #前面的1为指定位置添加
print(b)
['liuchen', 'lindonglin']
3. 列表的修改
a=['香蕉','那你','小丑','撒旦','娜娜']
a[-2]=['女路']
print(a)
['香蕉', '那你', '小丑', ['女路'], '娜娜']
另一种方法:
a=['香蕉','那你','小丑','撒旦','娜娜']
for i in range(len(a)):
if '小丑' in a[i]:
a[i]='大笔'
print(a)
['香蕉', '那你', '大笔', '撒旦', '娜娜']
4. 列表的删除
a=['香蕉','那你','小丑','撒旦','娜娜']
del a[-1]
print(a)
['香蕉', '那你', '小丑', '撒旦']
或
a=['香蕉','那你','小丑','撒旦','娜娜']
a.remove('那你')
print(a)
['香蕉', '小丑', '撒旦', '娜娜']
或
a=['香蕉','那你','小丑','撒旦','娜娜']
a.pop(3)
print(a)
['香蕉', '那你', '小丑', '娜娜']
5. 列表切片
animals = ['cat','dog','tiger','snake','mouse','bird']
print(animals[2:5])
print(animals[-1:])
print(animals[-3:-1])
print(animals[-5:-1:2])#后面的2表示的是空一个显示
print(animals[::2])
['tiger', 'snake', 'mouse']
['bird']
['snake', 'mouse']
['dog', 'snake']
['cat', 'tiger', 'mouse']
6. 随机生成20个数存到列表中
import random
list=[]
for i in range(20):
run=random.randint(1,20)
if run not in list:
list.append(run)
print(list)
[7, 15, 16, 9, 6, 2, 17, 11, 3]#这里为什么少于20个,原因是随机到了重复的数字
随机生成10个不重复的数存到列表中
import random
i=0
list=[]
while i<10:
run= random.randint(1,20)
if run not in list:
list.append(run)
i+=1
print(list)
[11, 5, 2, 15, 17, 13, 20, 3, 1, 12]
7. 列表中升序排序和倒叙排序
import ranadom
list=[]
i=0
while i<10:
run=random.randint(1,20)
if run not in list:
list.append (run)
i+=1
new_list=sorted(list)#默认升序排列
print(new_list)
[2, 5, 9, 10, 14, 15, 17, 18, 19, 20]
降序
import random
list=[]
i=0
while i<10:
run=random.randint(1,20)
if run not in list:
list.append (run)
i+=1
new_list=sorted(list,reverse=True)#T要大写这里
print(new_list)
[15, 14, 12, 11, 9, 7, 6, 5, 2, 1]
元组
1. 元组不能修改,但可以把列表转变成元组
import random
list=[]
i=0
while i<10:
run=random.randint(1,20)
if run not in list:
list.append (run)
i+=1
new_list=tuple(list)
print(new_list)
print(type(new_list))
(16, 14, 20, 19, 1, 6, 9, 13, 7, 17)
<class 'tuple'>
2. 元组赋值给变量
t3=(1,2,3)
a,b,c=t3
print(a)
print(b)
1
2
3. 元组中x的个数
t3=(1,2,3,'x','x')
print(t3.count('x'))
2