简体   繁体   English

如何在 Python 中检查列表推导式中的函数条件

[英]How to check the function condition inside the list comprehension in Python

Hi i was trying to find out if there is a way to do it.嗨,我想知道是否有办法做到这一点。

number_list = [d(x) for x in range(1, 10001) if d(x) < 10000]

I want to use list comprehension something like this.我想使用这样的列表理解。

So basically, I want to have a list items with the function result that is less than 10000.所以基本上,我想要一个函数结果小于 10000 的列表项。

Is there a way to check the condition of the function and put it into the list by using list comprehension?有没有办法通过使用列表理解来检查函数的条件并将其放入列表中?

start with a generator从发电机开始

a_generator = (d(x) for x in a_list)
# a generator will only evaluate when iterated
my_list = [v for v in a_generator if v < 1000]
# all values should be less than 1000 in this example
max(my_list) # better be less than 1000

if the values in a_list are sorted from low to high and the rule of如果a_list中的值从低到高排序并且规则

d(x) < d(x + 1) is followed you can optimize it further d(x) < d(x + 1)之后你可以进一步优化它

import itertools
a_generator = (d(x) for x in my_sorted_list)
my_list = list(itertools.takewhile(lambda v:v < 1000, a_generator))
# this one will only calculate while the result meets the condition
# once a single value exceeds it will stop taking values

you can of coarse easily transform either of these into a single line您可以粗略地轻松地将其中任何一个转换为一行

[v for v in (d(x) for x in a_list) if v < 1000]

and

list(itertools.takewhile(lambda v:v < 1000,  (d(x) for x in my_sorted_list)))

respectively, but future you and anyone you work with would probably prefer it on 2 lines分别,但未来你和你一起工作的任何人可能更喜欢它在 2 行

You can write comprehension as follows:你可以写理解如下:

res = [d(x) if d(x) < 10000 else None for x in range(1, 10001)]
number_list = [i for i in res if i is not None]

List comprehensions can have two spots where if/else can be used:列表推导式可以有两个地方可以使用 if/else:

foo = [{x if <smth> else y if <smth_else> else z} for i in range(1000) {if i % 2 == 0}]

The first if-else (inside first pair of curly brackets) determines what exactly to put in your list and the second if statement (second pair of curly brackets) determines when to do it.第一次的if-else(内第一对大括号)决定究竟是什么把你的列表和第二if语句(第二对大括号)决定什么时候做。

Note: curly brackets are for display purposes only.注意:大括号仅用于显示目的。 They shouldn't be used in the actual code.不应在实际代码中使用它们。

For example a list comprehension of FizzBuzz would look like this:例如,FizzBu​​zz 的列表推导如下所示:

fb = ['FizzBuzz' if i % 15 == 0 
      else 'Fizz' if i % 3 == 0 
      else 'Buzz' if i % 5 == 0 
      else str(i) 
      for i in range(1, 100)]

EDIT: Updated as per Joran's comment.编辑:根据乔兰的评论更新。 I forgot that else statement is necessary when using if-else in the front part of comprehension.我忘了在理解前部分使用 if-else 时需要 else 语句。

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

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