避免三个for循环

时间:2017-05-18 17:08:24

标签: python for-loop

有没有办法可以优化下面的代码,而不使用3 for-loops

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]

4 个答案:

答案 0 :(得分:4)

您可以使用列表推导

# 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]

答案 1 :(得分:2)

这是使用列表理解的一个班轮:

anotherArray = [a for a in anotherArray if a in {obj.key for obj in firstArray}]

创建新列表比从现有列表中删除元素更容易。

答案 2 :(得分:2)

怎么样

anotherSet = set.intersection(set(obj.key for obj in firstArray), set(anotherArray))

返回newListKeysanotherArray之间通用的唯一键集。如果需要列表,可以转换为列表:anotherArray = list(set.intersection(newListKeys, set(anotherArray)))。请注意,它只会返回anotherArray中每个键的一个副本,但如果它是一个键列表,则它不能重复。

答案 3 :(得分:1)

另一个班轮选项:

SELECT name, guestCount from Table
   as A outer join (SELECT guestOf , count(*) 
   AS GuestCount FROM Table group by guestOf) 
   as GuestCounts WHERE  A.id = GuestCounts.guestOf