Lista jednoliniowa: warianty if-else

Chodzi bardziej o składnię rozumienia list Pythona. Mam listę, która tworzy listę liczb nieparzystych z danego przedziału:

[x for x in range(1, 10) if x % 2]

To tworzy filtr - mam listę źródeł, gdzie usuwam liczby parzyste (if x % 2). Chciałbym użyć czegoś takiego jak "jeśli-wtedy-else" tutaj. Następujący kod:

>>> [x for x in range(1, 10) if x % 2 else x * 100]
  File "<stdin>", line 1
    [x for x in range(1, 10) if x % 2 else x * 100]
                                         ^
SyntaxError: invalid syntax

Istnieje wyrażenie Pythona takie jak if-else:

1 if 0 is 0 else 3

Jak go używać wewnątrz listy?

Author: GG., 2013-06-26

5 answers

x if y else z jest składnią wyrażenia zwracanego dla każdego elementu. Dlatego potrzebujesz:

[ x if x%2 else x*100 for x in range(1, 10) ]

Zamieszanie wynika z faktu, że używasz filtra w pierwszym przykładzie, ale nie w drugim. W drugim przykładzie tylko odwzorowujesz każdą wartość na inną, używając wyrażenia trójdzielnego operatora.

Z filtrem potrzebujesz:

[ EXP for x in seq if COND ]

Bez filtra potrzebujesz:

[ EXP for x in seq ]

I w twoim drugim przykładzie wyrażenie jest " złożone" jeden, który wiąże się z if-else.

 224
Author: shx2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-18 13:01:47
[x if x % 2 else x * 100 for x in range(1, 10) ]
 15
Author: lucasg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-26 13:19:43

Just another solution, hope some one may like it :

Using: [False, True] [Expression]

>>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10))
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
 10
Author: James Sapam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-18 12:54:12

Możesz to zrobić również ze zrozumieniem listy:

    A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
    print A
 9
Author: Stefan Gruenwald,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-29 07:40:36

Udało mi się to zrobić

>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
    [1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
 2
Author: anudeep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-11 08:43:38