python常用操作汇总

python创建二维数组

python创建三行三列的二维数组,下面方法是错误的,因为是浅拷贝:

lst1 = [0] * 3
lst2 = [lst1] * 3
lst2[1][1] = 2
print(lst2) # [[0, 2, 0], [0, 2, 0], [0, 2, 0]]

正确姿势

lst = [[0 for j in range(3)] for i in range(3)]
lst[1][1] = 2

python获取数据的下标

lst = [1,2,3,4,5]
pos = lst.index(3)
print(pos) # 2

python数组去重

lst = [2,2,3,4,4]
print(list(set(lst))) # [2, 3, 4]
dic = {}
# 增
dic[1] = '苏'
dic[2] = '苏1'
dic[3] = '苏2'
dic[4] = '你'
print(dic) # {1: '苏', 2: '苏1', 3: '苏2', 4: '你'}
# 删
del dic[1]
print(dic) # {2: 'su1', 3: 'su2', 4: '你'}
# 改
dic[2] = '张'
# 查
print(dic[2]) # 张
print(dic.get(3, None)) # 苏2
print(dic.get(5, None)) # None
print(2 in dic) # True

print(dic.keys())
print(dic.values())

for i in enumerate(dic):
    print(i)

你可能感兴趣的:(python)