有没有一种方法可以在不使用 3 个 for 循环的情况下优化下面的代码
for obj in firstArray:
newListKeys.append(obj.key)
for key in anotherArray:
if key not in newListKeys:
soonToDelete.append(key)
for key in soonToDelete:
del anotherArray[key]
请您参考如下方法:
你可以使用列表理解
# This replaces the first for loop
newListKeys = [obj.key for obj in firstArray]
# This replaces the second and third loops
anotherArray = [item for item in anotherArray if item in newListKeys]
