Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中迭代列表头的优雅方式_Python_List_Iteration_Generator - Fatal编程技术网

在Python中迭代列表头的优雅方式

在Python中迭代列表头的优雅方式,python,list,iteration,generator,Python,List,Iteration,Generator,假设我有一个[“a”、“b”、“c”、“d”] 我正在寻找一个蟒蛇习语来大致描述这一点: for first_elements in head(mylist): # would first yield ["a"], then ["a", "b], then ["a", "b", "c"] # until the whole list gets generated as a result, after which the generator # terminates. 我的感觉

假设我有一个
[“a”、“b”、“c”、“d”]

我正在寻找一个蟒蛇习语来大致描述这一点:

for first_elements in head(mylist):
   # would first yield ["a"], then ["a", "b], then ["a", "b", "c"]
   # until the whole list gets generated as a result, after which the generator
   # terminates.
我的感觉告诉我,这应该是内在的,但我一直在逃避。怎么 你会这么做吗?

你是说这个吗

def head(it):
    val = []
    for elem in it:
        val.append(elem)
        yield val
这需要任何iterable,而不仅仅是列表

演示:

我可以这样做:

def head(A) :
    for i in xrange(1,len(A)+1) :
        yield A[:i]
例如:

for x in head(["a", "b", "c", "d"]) :
    print x

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']

当您生成一个元素,修改它,然后生成下一个元素时,这将如何表现?(并不是说这一定是个问题;肯定比每次创建一个新的列表更有效。)@tobias_k:这个列表是共享的,所以它会影响所有未来的收益率。如果您愿意,我们可以将其制作为一个元组,只需使用
yieldtuple(val)
:-)你真的需要iter吗?你能不能用一个简单的
来进行
循环(而不是
while
)?是的,这就是我的意思,它解决了问题。然而,当我实际上不需要临时变量时,我并不喜欢临时变量,所以我更喜欢返回切片的解决方案(尽管它可读性较差)。@Julik:考虑到该版本需要序列,我的版本也接受任何可迭代的(包括生成器)。我想这会更慢(渐进地)比Martijn Pieters的解决方案快,因为每次都会重新创建一个完整的新列表,但这比他的解决方案快,使用NumPy数组。@EOL对,但它有一个(可能)优点,即您可以自由操作生成的“头”。我正在勾选这个,由于以下原因,我喜欢它:1)我正在应用它的数据集很小b)我不喜欢临时变量-即使在额外列表中累积“head”是一个很好的推测动作,不生成额外列表。或者使用
xrange(len(a))
然后
生成一个[:I+1]
。。。。或
对于i,在枚举(A)中:产生A[:i+1]
for x in head(["a", "b", "c", "d"]) :
    print x

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']