gpt4 book ai didi

python - 如何将 None 插入列表?

转载 作者:太空狗 更新时间:2023-10-30 01:40:23 25 4
gpt4 key购买 nike

运行

L = [1,2,3,4,5,6]
print zip(L,L[1:])[::2]

yields

[(1, 2), (3, 4), (5, 6)]

将产生什么 zip(或其他)语句

[1, 2, None, 3, 4, None, 5, 6, None]

?

更新

开始就很好

L = [(1,2),(3,4),(5,6)]

只要声明保持(快速)单行即可。

更新2

插入 None 的一个用例是 plot segments quickly .

最佳答案

你可以这样做:

>>> L = [1,2,3,4,5,6]
>>> it = zip(*[iter(L)] * 2)
>>> [y for x in it for y in x + (None,)]
[1, 2, None, 3, 4, None, 5, 6, None]

性能和空间复杂性明智的 @mgilson 的方法如果稍微修改是最好的方法之一:

>>> from itertools import izip, chain
>>> L = [1,2,3,4,5,6]*10**5
>>> %timeit [y for x in zip(*[iter(L)] * 2) for y in x + (None, )]
10 loops, best of 3: 47.2 ms per loop

如果我们删除列表推导式并使用 itertools.chain.from_iterable 那么您会看到显着的改进:

>>> %timeit list(chain.from_iterable(x + (None,) for x in izip(*[iter(L)] * 2)))
10 loops, best of 3: 31.8 ms per loop
>>> %timeit list(insert_none_while(L)) # mgilson's approach
10 loops, best of 3: 50.7 ms per loop
>>> %timeit list(insert_none_for(L))
10 loops, best of 3: 32.6 ms per loop

这里insert_none_while是@mgilson的原始代码,insert_none_for是:

def insert_none_for(iterable):
it = iter(iterable)
for x in it:
yield x
yield next(it)
yield None

更新

@Padraic Cunningham 提出的解决方案的略微修改版本似乎是最快的(当与 itertools.izip 一起使用时,与 @Jochen Ritzel 解决方案相比只有一点点差距):

>>> L = [1,2,3,4,5,6]*10**6
>>> %timeit [y for x in zip(*[iter(L)] * 2) for y in x + (None, )]
1 loops, best of 3: 541 ms per loop
>>> %timeit list(chain.from_iterable(x + (None,) for x in izip(*[iter(L)] * 2)))
1 loops, best of 3: 349 ms per loop
# Using while 1 and cached next function
>>> %timeit list(insert_none_while_one(L))
1 loops, best of 3: 470 ms per loop
# Cached next function
>>> %timeit list(insert_none_for(L))
1 loops, best of 3: 351 ms per loop
# Jochen Ritzel's original solutions
>>> %timeit it = iter(L); list(itertools.chain.from_iterable(zip(it, it, repeat(None))))
1 loops, best of 3: 352 ms per loop
# Jochen Ritzel's solutions using izip
>>> %timeit it = iter(L); list(itertools.chain.from_iterable(izip(it, it, repeat(None))))
10 loops, best of 3: 167 ms per loop
# Padraic Cunningham's solution using slicing
>>> %timeit list(chain.from_iterable(izip_longest(L[::2],L[1::2],[None])))
1 loops, best of 3: 236 ms per loop
# Padraic Cunningham's solution using iter
>>> %timeit it=iter(L); list(chain.from_iterable(izip_longest(it, it, [])))
10 loops, best of 3: 156 ms per loop
# Kasra
>>> %timeit list(chain(*[L[i:i+2]+[None] for i in range(0,len(L),2)]))
1 loops, best of 3: 1.43 s per loop

还是不够好?

考虑使用 NumPy 数组:

>>> arr = np.array(L, dtype=float)
>>> arr.size
6000000
>>> %timeit np.insert(arr.reshape(-1, 2), 2, None, axis=1).ravel()
10 loops, best of 3: 80.8 ms per loop

相关:How does zip(*[iter(s)]*n) work in Python?

关于python - 如何将 None 插入列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28096920/

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