如何修改Python字典代码以忽略未定义键并找出数组公共元素
解决字典访问不存在键报错的问题
你的代码报错是因为直接访问字典中不存在的键时,Python会抛出KeyError。以下两种简单修改方式可以让代码正常运行:
方法1:使用字典的get()方法
get()方法允许指定键不存在时的默认返回值(默认是None),不会触发报错。修改判断条件即可:
import numpy as np A = np.random.randint(1, 10, 15) B = np.random.randint(1, 15, 15) print(A) print(B) dic = {} for x in A: dic[x] = 1 for y in B: # 键存在时返回1(布尔值为True),不存在返回None(布尔值为False) if dic.get(y): print("the common element is ", y)
方法2:用in关键字判断键是否存在
直接检查元素是否属于字典的键,这是判断字典键存在性最直观高效的方式:
import numpy as np A = np.random.randint(1, 10, 15) B = np.random.randint(1, 15, 15) print(A) print(B) dic = {} for x in A: dic[x] = 1 for y in B: if y in dic: print("the common element is ", y)
额外优化:避免重复打印相同元素
如果B中存在重复的公共元素,上面的代码会重复输出。若只想获取唯一的公共元素,可以先将B转为集合再遍历:
for y in set(B): if y in dic: print("the common element is ", y)
内容的提问来源于stack exchange,提问作者Marcusaurelius
相关产品推荐
相关产品推荐

