M
M
MonsterAndrew2018-06-22 03:12:07
Python
MonsterAndrew, 2018-06-22 03:12:07

How can this Python code be simplified?

There is a code:

for player in players:
    if player["id"] == user_id: return player
    else: return False

How can you fit it in one line?
PS I tried like this: return [d for d in players if d["id"] == user_id], but then it returns not False, but an empty array. It would be desirable that if if does not work returned False.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
planc, 2018-06-22
@planc

next((d for d in players if d["id"] == user_id), False)

S
SexyHair, 2018-06-22
@SexyHair

Why is there a loop at all if after the first iteration either player or False will
return anyway return players[0] if players[0]['id'] == user_id else False
PS Answer to your "PS"
Try return [d for d in players if d["id"] == user_id] or False

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question