[英]How do i write this in list comprehension in python
I want to write a list comprehension that will have print an element out of an array every other element.我想编写一个列表理解,它将每隔一个元素从数组中打印一个元素。 How do I do so?我该怎么做?
for item in results:
record = extract_record(item)
if record:
records.append(record)
in Python 3.8 or later you could make use of the assignment expression and do something like在 Python 3.8 或更高版本中,您可以使用赋值表达式并执行类似的操作
records = [record for item in results if (record := extract_record(item))]
This avoids having to extract the record twice.这避免了必须提取记录两次。
The list comprehension equivalent of the above will be:与上述等效的列表理解将是:
records = [extract_record(item) for item in results if extract_record(item)]
Note that extract_record()
is needed twice and hence not so useful.请注意, extract_record()
需要两次,因此没那么有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.