python - 内存高效填充列表

标签 python

我有一个 list

a = ['a', 'b', 'c']

给定长度,我想在要获取的每个项目之后插入某个元素 'x'

ax = ['a', 'x', 'b', 'x', 'c', 'x']

由于元素很大,我不想做很多pop或子列表。

有什么想法吗?

最佳答案

由于列表很大,最好的方法是使用生成器,就像这样

def interleave(my_list, filler):
    for item in my_list:
        yield item
        yield filler

print list(interleave(['a', 'b', 'c'], 'x'))
# ['a', 'x', 'b', 'x', 'c', 'x']

或者你可以像这样返回一个链式迭代器

from itertools import chain, izip, repeat
def interleave(my_list, filler):
    return chain.from_iterable(izip(my_list, repeat(filler)))
  1. repeat(filler) 返回一个给 filler 无限次的迭代器。

  2. izip(my_list, repeat(filler)) 返回一个迭代器,一次从 my_listrepeat(filler )。所以,list(izip(my_list, repeat(filler))) 的输出看起来像这样

    [('a', 'x'), ('b', 'x'), ('c', 'x')]
    
  3. 现在,我们所要做的就是展平数据。因此,我们将 izip 的结果与 chain.from_iterable 链接起来,一次从 iterable 中给出一个值。

关于python - 内存高效填充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22831271/

相关文章:

python - 使用python在json中设置日期时间对象

python - 两个 3-D 数组上的 numpy.maximum()

arguments - 选择 2-3 个选项作为函数参数的 Pythonic 方式

python - APScheduler 会跳过作业并在其他时间运行

performance - Python,迭代正则表达式但在第一次匹配时停止的最快方法

python - 如何在SqlAlchemy中使用 "CONVERT"函数?

python - 如何在pypy沙箱中导入numpy

python - 如何根据数据框的其他列创建新的 Pandas 列?

python - 如何使用 smtplib 在 Python 中验证电子邮件地址

python - 从另一个 python 脚本运行一个 python 脚本并将变量传递给它