python:如何在列表生成器表达式中获取列表长度?(python: how to get list length in list generator expression?)
也许这样(只是一个伪代码)
li = [1,2,3,4,5,6]
a = [d for d in li if self.length<3]
print a
[1,2]
什么是pythonic方式来做那件事?
Maybe like this (just a pseudocode)
li = [1,2,3,4,5,6]
a = [d for d in li if self.length<3]
print a
[1,2]
What is a pythonic way to do that thing?
原文:https://stackoverflow.com/questions/39973542
更新时间:2020-03-22 14:03
最满意答案
您可以使用itertools.count()来跟踪您使用的元素数量:
from itertools import count
li = [1,2,3,4,5,6]
c = count(1) # initialize to 1
a = [d for d in li if next(c) < 3] # everytime you add an element
print (a) # in the comprehension `c` is incremented
它跟踪添加到列表中的元素,因此列表的长度给出