-3
\$\begingroup\$

I'm using a list comprehension to find an object that matches in two lists and return the object for its property. I know the object ALWAYS exists in both lists and no other item in the lists are shared but I don't know which one it is so I can't just reference it from the list.

The code I can give you is:

class BaseballCard:

    ...

    @staticmethod
    def load_from_matching_player_with_other_org(organization, other_org):
        """Determine matching pair of the same player and create Baseball Card."""
        return BaseballCard(*[player for player in organization.players if player in other_org][0].stats)

     ...

Is there a better or simpler way to do this part?

[player for player in organization.players if player in other_org][0]

Topic slightly changed to protect sensitive data

\$\endgroup\$

closed as off-topic by Ludisposed, IEatBagels, Gareth Rees, Sᴀᴍ Onᴇᴌᴀ, Mast Oct 17 '18 at 5:11

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – Ludisposed, IEatBagels, Gareth Rees, Sᴀᴍ Onᴇᴌᴀ, Mast
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    \$\begingroup\$ This question was discussed in chat. \$\endgroup\$ – 200_success Dec 17 '14 at 7:08
  • \$\begingroup\$ moar downvotes, plz. They def make me better developer. As they say, "A downvote is worth a trillion comments." \$\endgroup\$ – groteworld Dec 17 '14 at 19:21
5
\$\begingroup\$

You can use next with a generator expression. Here instead of creating a list of all matching items next will simply return the first item from the generator passed to it:

next(player for player in organization.players if player in other_org.players).stats

Just in case other_org.players is huge and all items in both lists are hashable then better convert other_org.players to a set first to support fast lookups:

other_org_set = set(other_org.players)
next(player for player in organization.players if player in other_org_set).stats

Note that both solutions above assume there's always at least one such maching items, if that's not the case then better return a sentinel value(usually None and object() are used) from next and then try to access pror based on the return value from next:

matching_player = next((player for player in organization.players if player in other_org.players), None)
if matching_player is not None:
    return BaseballCard(matching_player.stats)
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.