Для единственного числа if
синтаксис:
[print("YAY") for c,v in zip(conditions,values) if c==v]
Это означает:
for c,v in zip(conditions,values):
if c==v:
print('YAY')
Для нескольких if
и elif
и else
,синтаксис:
[print("YAY") if c==v else print("lalala") if c=='some other condition' else print("NAY") for c,v in zip(conditions,values)]
Это переводит на
for c,v in zip(conditions,values):
if c==v:
print('YAY')
elif c=='some other condition':
print('lalala')
else:
print('NAY')
Мы можем проверить это:
conditions = [1, 2, 3, 4, 'some other condition']
values = [1, 2, 3, 3, 999]
[print("YAY") if c==v else print("lalala") if c=='some other condition' else print("NAY") for c,v in zip(conditions,values)]
#YAY
#YAY
#YAY
#NAY
#lalala
РЕДАКТИРОВАТЬ: Если вы хотите обрабатывать вложенные циклы for
в понимании списка, обратите внимание, что следующий код эквивалентен:
newlist = []
for c in conditions:
for v in values:
newlist.append((c,v))
print (newlist)
# [(1, 1), (1, 2), (1, 3), (1, 3), (1, 999), (2, 1), (2, 2), (2, 3), (2, 3), (2, 999), (3, 1), (3, 2), (3, 3), (3, 3), (3, 999), (4, 1), (4, 2), (4, 3), (4, 3), (4, 999), ('some other condition', 1), ('some other condition', 2), ('some other condition', 3), ('some other condition', 3), ('some other condition', 999)]
и
newlist = [(c,v) for c in conditions for v in values]
print (newlist)
#[(1, 1), (1, 2), (1, 3), (1, 3), (1, 999), (2, 1), (2, 2), (2, 3), (2, 3), (2, 999), (3, 1), (3, 2), (3, 3), (3, 3), (3, 999), (4, 1), (4, 2), (4, 3), (4, 3), (4, 999), ('some other condition', 1), ('some other condition', 2), ('some other condition', 3), ('some other condition', 3), ('some other condition', 999)]
Обратите внимание, что for c in conditions
является внешним циклом и for v in values
является внутренним циклом для обоихфрагменты кода