【Python-列表操作和方法】赋值/修改/切片等

#列表和元祖
#列表list可修改,元祖tuple不可修改
print(">>>Basic Operation of List<<<")
x=[1,1,1]
print("1.Give Value")


print(x)
x[1]=2
print("After Give value:",x)
print('\n')


print("2.Delete")
del x[2]
print("After delete value:",x)
print('\n')


print("3.切片赋值")
x[1:]=list('hello')
print(x)
print('\n')


print("4.切片Insert")
x[1:1]=[2,3,5]
print(x)
print('\n')


print(">>>Method of List<<<")
print("1.append")
x.append(3)
print("x.append(3) = ",x)
x.append('3')
print("x.append('3') = ",x)
print('\n')


print('2.clear')
print('x.clear()')
print('\n')


print('3.copy')
print('b=a.copy()')
print('\n')


print('4.count')
#元素出现的次数
print('x.count(1) = ',x.count(1))
print('\n')


print('5.extend')
b=[2]
x.extend(b)
print('b=[2] ,x.extend(b) = ',x)
print('\n')


print('6.index')
print("x.index('h') = ",x.index('h'))
print('\n')


print('7.insert')
x.insert(1,'h')
print("x.insert(1,'h') :",x)
print('\n')


print('8.pop')
#删除一个元素,并返回该元素
#默认从末尾删除
x.pop()
print("x.pop() = ",x.pop())
x.pop(1)
print("x.pop(1) = ",x.pop(1))
x.pop(2)
print("x.pop(2)= ",x.pop(2))
print('\n')


print('9.remove')
x.remove('l')
print("x.remove('l')",x)
print('\n')


print('10.reverse')
x.reverse()
print("x.reverse() = ",x)
print('\n')


print('11.sort')
#不同类型的不可排序
a = [1,8,33,2,41,0]
a.sort()
print("[1,8,33,2,41,0].sort() = ",a)
print('\n')

>>>Basic Operation of List<<<
1.Give Value
[1, 1, 1]
After Give value: [1, 2, 1]


2.Delete
After delete value: [1, 2]


3.切片赋值
[1, 'h', 'e', 'l', 'l', 'o']


4.切片Insert
[1, 2, 3, 5, 'h', 'e', 'l', 'l', 'o']


>>>Method of List<<<
1.append
x.append(3) =  [1, 2, 3, 5, 'h', 'e', 'l', 'l', 'o', 3]
x.append('3') =  [1, 2, 3, 5, 'h', 'e', 'l', 'l', 'o', 3, '3']


2.clear
x.clear()


3.copy
b=a.copy()


4.count
x.count(1) =  1


5.extend
b=[2] ,x.extend(b) =  [1, 2, 3, 5, 'h', 'e', 'l', 'l', 'o', 3, '3', 2]


6.index
x.index('h') =  4


7.insert
x.insert(1,'h') : [1, 'h', 2, 3, 5, 'h', 'e', 'l', 'l', 'o', 3, '3', 2]


8.pop
x.pop() =  3
x.pop(1) =  2
x.pop(2)=  h


9.remove
x.remove('l') [1, 3, 'e', 'l', 'o', 3]


10.reverse
x.reverse() =  [3, 'o', 'l', 'e', 3, 1]


11.sort
[1,8,33,2,41,0].sort() =  [0, 1, 2, 8, 33, 41]

注意:使用Sort时,

1.不同类型的元素集合不可进行排序,如str和int

2.要将结果赋值,应该调用sorted,而不是sort

你可能感兴趣的:(Python)