简体   繁体   English

嵌套 ifs 中的列表理解

[英]List comprehension in nested ifs

I am a newbie trying to understand list comprehensions in python. My question is different from another posts.我是一个新手,试图了解 python 中的列表理解。我的问题与其他帖子不同。

I was asked to write list comprehension code to get the following output:我被要求编写列表理解代码以获得以下 output:

All odd numbers from 1 to 30 (both inclusive).从 1 到 30(包括两者)的所有奇数。 Those that are multiples of 5 will be marked with an 'x'.那些是 5 的倍数的将标有“x”。

[1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29] [1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]

For this, I tried to get it with normal for and if ways.为此,我尝试使用正常的 for 和 if 方法来获取它。 This is my solution and it worked:这是我的解决方案并且有效:

odds = []

for i in list(range(1,30+1)):
  if i%2 !=0:
    odds.append(i)
    if i%5 == 0:
      odds.append(f'{i}x')
      odds.remove(i)

print(odds)

In the image you can find my failed list comprehension attempt.在图像中,您可以找到我失败的列表理解尝试。 I need some light to place the rest of the stuff correctly.我需要一些光来正确放置 rest 的东西。

Thank you!谢谢!

在此处输入图像描述

You cannot solve this problem in one line using list comprehension alone.您不能单独使用列表理解在一行中解决这个问题。 You need the ternary operator (enclosed in the parentheses).您需要三元运算符(括在括号中)。

[(n if n%5 else f'{n}x') for n in range(1,31) if n%2]

If you don't care about the order of the items, you can avoid needing the ternary operator ( conditional expression ) by concatenating the lists resulting from two list comprehensions, eg如果您不关心项目的顺序,则可以通过连接两个列表理解产生的列表来避免需要三元运算符( 条件表达式),例如

[n for n in range(1,31,2) if n%5 != 0] + [f'{n}x' for n in range(1,31,2) if n%5 == 0]

... which produces: ...产生:

[1, 3, 7, 9, 11, 13, 17, 19, 21, 23, 27, 29, '5x', '15x', '25x'] [1, 3, 7, 9, 11, 13, 17, 19, 21, 23, 27, 29, '5x', '15x', '25x']

Alternatively, at the risk of making this look like code golf:或者,冒着使它看起来像代码高尔夫的风险:

[[f'{n}x',n][min(n%5,1)] for n in range(1,31,2)]

... produces: ... 产生:

[1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29] [1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]

I've used the expression min(n%5,1) to index the list [f'{n}x',n] and thus select either item 0 or item 1 in the list, depending on whether n is divisible by 5 or not -- also without using the conditional expression .我使用表达式min(n%5,1)来索引列表[f'{n}x',n] ,因此 select 列表中的项目 0 或项目 1,具体取决于n是否可以被 5 整除or not - 也不使用条件表达式

Alternate workaround:替代解决方法:

numlist = [(i,f'{i}x')[not i%5] for i in range(31) if i%2]
print(numlist)
# [1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM