面试宝典
1.列表
lst = [1, 2]
lst[0] = lst
print(lst)
结果:[[...], 2]
*****
lst = [1,2]
for i in lst:
lst.append("alex")
print(lst)
每次循环都加了一个"alex",所以for循环就一直在执行
结果:不会打印内容
lst = [1,2]
for i in lst:
lst.append("alex")
print(lst)
结果:循环打印lst中的内容,此循环是死循环
lst= [1,2,3,4,5]
for i in lst:
lst.pop()
print(lst)
结果:[1,2]
lst= [1,2,3,4,5]
for i in range(len(lst)):
lst.pop()
print(lst)
结果:[]
lst = []
for i in range(5):
lst.append([])
print(lst)
结果:[[], [], [], [], []]
lst = []
for i in lst:
lst.append("alex")
print(lst)
结果:不进行循环
2.字符串
s = "给阿姨倒一杯卡布奇诺"
print(s[::-1])
3.字典 (用一行代码将a,b的值交换)
a = 10
b = 20
a,b = b,a
print(a,b)
4.集合,对列表去重
lst = [1,2,1,2,4,2,45,3,2,45,2345,]
print(list(set(lst)))
5.利用for循环删除掉列表中的每一个元素
利用for循环删除列表的元素
第一种:
lst = [1,2,3,4]
for i in range(len(lst)):
del lst[-1]
print(lst)
第二种:
lst = [1,2,3,4]
for i in range(len(lst)-1,-1,-1):
del lst[i]
print(lst)
第三种:
lst = [1,2,3,4]
for i in range(len(lst)):
lst.pop()
print(lst)
第四种:
lst = [1,2,3,4]
lst2 = lst.copy()
for i in lst2:
lst.remove(i)
print(lst)
后续持续更新...