开发者

if typeA in [typeB.typeA for typeB in typeBlist]: ... accessing typeB within the if clause?

开发者 https://www.devze.com 2023-03-25 01:54 出处:网络
The full example code: for开发者_运维问答 typeA in typeAlist: if typeA in [typeB.typeA for typeB in typeBlist]:

The full example code:

for开发者_运维问答 typeA in typeAlist:
  if typeA in [typeB.typeA for typeB in typeBlist]:
    return typeB

Obviously that doesn't work, but it feels like there would be a neat way to retrieve the typeB object that matched the typeA object.

The only way I can think of making it work is to have a nested for loop, iterating over typeBlist until the typeA attribute matches, then breaking. Is there a cleaner way? Or is that actually sufficiently clean?


You can use a if within your list comprehension:

[typeB for typeB in typeBlist if typeB.typeA == typeA]

This would return all the members of typeBlist for which typeB.typeA == typeA.

If you're sure there's only a single match you can use a generator expression to stop working through the whole list:

try:
    return (typeB for typeB in typeBlist if typeB.typeA == typeA).next()
except StopIteration:
    return None

If you're doing this lookup a lot it might be easier to create a dict to map from typeA to typeB.

lookup = dict((typeB.typeA,typeB) for typeB in typeBlist)

You can then re-use this like so:

typeB = lookup[typeA]

If you might have many typeB entries for each typeA your lookup would map typeA to a list of typeBs:

from collections import defaultdict
lookup = defaultdict(list)
for typeB in typeBlist:
    lookup[typeB.typeA].append(typeB)


How about:

matching_typeBs = [ x for x in typeBlist if x.typeA in typeAlist ]


Or the very same with filter statement(note that it is on your own to choose whether to use filter or list comprehension but second one is usually faster):

filter(lambda x: x.typeA in typeAlist, typeBlist)
0

精彩评论

暂无评论...
验证码 换一张
取 消