gpt4 book ai didi

python - 在列表中动态生成列表元素

转载 作者:太空狗 更新时间:2023-10-29 19:37:12 25 4
gpt4 key购买 nike

我有一个列表,它由以下元素组成,

list1 = [a1,a2,a3]

这个列表的每个元素本身可以是一个可变大小的列表,例如,

a1 = [x1,y1,z1], a2 = [w2,x2,y2,z2], a3 = [p3,r3,t3,n3]

我可以直接设置一个循环遍历 list1 的生成器,并生成每个元素的成分;

array = []
for i in list1:
for j in i:
array.append[j]
yield array

但是,有没有一种方法可以指定数组的大小?

例如 - 批量大小为两个;

1st yield : [x1,y1]
2nd yield : [z1,w1]
3rd yield : [x2,y2]
4th yield : [z2,p3]
5th yield : [r3,t3]
6th yield : [n3]
7th yield : repeat 1st

或批量大小为 4;

1st yield : [x1,y1,z1,w1]
2nd yield : [x2,y2,z2,p3]
3rd yield : [r3,t3,n3]
4th yield : repeat first

对于不同大小的列表执行此操作似乎很重要,每个列表都包含其他不同大小的列表。

最佳答案

这很简单,实际上,使用 itertools:

>>> a1 = ['x1','y1','z1']; a2 = ['w2','x2','y2','z2']; a3 = ['p3','r3','t3','n3']
>>> list1 = [a1,a2,a3]
>>> from itertools import chain, islice
>>> flatten = chain.from_iterable
>>> def slicer(seq, n):
... it = iter(seq)
... return lambda: list(islice(it,n))
...
>>> def my_gen(seq_seq, batchsize):
... for batch in iter(slicer(flatten(seq_seq), batchsize), []):
... yield batch
...
>>> list(my_gen(list1, 2))
[['x1', 'y1'], ['z1', 'w2'], ['x2', 'y2'], ['z2', 'p3'], ['r3', 't3'], ['n3']]
>>> list(my_gen(list1, 4))
[['x1', 'y1', 'z1', 'w2'], ['x2', 'y2', 'z2', 'p3'], ['r3', 't3', 'n3']]

注意,我们可以在 Python 3.3+ 中使用 yield from:

>>> def my_gen(seq_seq, batchsize):
... yield from iter(slicer(flatten(seq_seq), batchsize), [])
...
>>> list(my_gen(list1,2))
[['x1', 'y1'], ['z1', 'w2'], ['x2', 'y2'], ['z2', 'p3'], ['r3', 't3'], ['n3']]
>>> list(my_gen(list1,3))
[['x1', 'y1', 'z1'], ['w2', 'x2', 'y2'], ['z2', 'p3', 'r3'], ['t3', 'n3']]
>>> list(my_gen(list1,4))
[['x1', 'y1', 'z1', 'w2'], ['x2', 'y2', 'z2', 'p3'], ['r3', 't3', 'n3']]
>>>

关于python - 在列表中动态生成列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45154543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com