python - 有效地将列表合并到稀疏列表中

标签 python list performance

我有两个列表:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]

我想合并它们,要么创建一个新列表,要么只更新 a,方法是用 b 中的值填充 Nones,所以

a = [7,8,1,2,4,3,6,5,9]

最有效的方法是什么?

为了扩展,我想对 b 的每个排列都执行此操作。这是否允许简化该技术?

最佳答案

这是一种方法。使用列表理解并将 b 转换为迭代器对象。

演示:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
b = iter(b)

print( [next(b) if i is None else i for i in a] )

输出:

[7, 8, 1, 2, 4, 3, 6, 5, 9]

关于python - 有效地将列表合并到稀疏列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50831284/

相关文章:

c# - List<T>().Count 线程安全吗?

python - 计算字符串 Python3.6 中子字符串实例的最快方法

performance - == 和 = := should I use? 中的哪一个

c++ - 表现。寻找子串。 substr 与查找

python - Python上传到YouTube OAuth2问题

python - Pandas:从 DataFrame 中删除所有带有 nans、0 和 NA 的列

python - 如何根据另一个列表中的值重新排列列表中的值?

python - 我的 python 代码中必须有主要功能吗?

flask 中的 python 装饰器

python - 查找列表中相差 1 的元素