【问题标题】:python - insert values from one list into another at pre-defined spotspython - 在预定义的位置将一个列表中的值插入另一个列表
【发布时间】:2017-02-09 14:54:02
【问题描述】:

在 Python (3.5) 中,如果我有一个像这样的长列表:

long_list = ['0','1','0','1','0','0'.'0'.'1','1','0']

还有一个长度等于 long_list 中 '1' 数量的较短列表,如下所示:

short_list = [8,7,6,5]

我将如何创建一个新列表,将我的 short_list 的值“插入”到我的 long_list 中的每个索引处,其中有一个“1”,并且为了保持一致性,将 long_list 中的“0”“替换”为一些数字(比如 99)。

我可以通过令人痛苦的 for 循环来做到这一点,但似乎应该有一种方法可以通过列表理解更有效地做到这一点,不是吗?

# bad solution
new_list = []
x = 0
for i in range(len(long_list)):
    if long_list[i] == '0':
        new_list.append(99)
    else:
        new_list.append(short_list[x])
        x += 1

期望的输出:

new_list = [99,8,99,7,99,99,99,6,5,99]

【问题讨论】:

  • 你确定short_list 中的值总是和long_list 中的'1' 一样多吗?
  • 是的,对于这个应用程序有。短名单来源于长名单。可能有太多信息无法解释实际用法(上面的示例是基于真实数据的玩具示例),但我确信短列表中的值与 '1' 的数量完全相同。

标签: python list for-loop list-comprehension


【解决方案1】:

short_list 转换为迭代器并使用列表推导从那里为每个'1' 获取值,否则使用固定值:

>>> long_list = ['0','1','0','1','0','0','0','1','1','0']
>>> short_list = [8,7,6,5]
>>> it = iter(short_list)
>>> [next(it) if x == '1' else 99 for x in long_list]
[99, 8, 99, 7, 99, 99, 99, 6, 5, 99]

这显然只适用于short_list 具有与long_list 上的1 相同数量或更多的元素。以上具有 O(n) 时间复杂度,其中 nlong_list 中的元素数量。请注意,这对所有类型的可迭代对象都是一样的,long_listshort_list 可能是生成器,最终结果将是相同的。

【讨论】:

  • 谢谢,这很好用而且速度非常快(在我的 200,000 多个项目的真实“long_list”上花费了不到一秒钟)。我应该更频繁地使用迭代器。
【解决方案2】:

如果更改short_list 没有问题,您可以使用list comprehension 尝试以下操作:

[short_list.pop(0) if i == '1' else 99 for i in long_list]

输出:

>>> long_list = ['0', '1', '0', '1', '0', '0', '0', '1', '1', '0']
>>> short_list = [8, 7, 6, 5]
>>>
>>> [short_list.pop(0) if i == '1' else 99 for i in long_list]
[99, 8, 99, 7, 99, 99, 99, 6, 5, 99]

【讨论】:

    【解决方案3】:

    并不是说这是最好的方法,但它不需要新的变量。

    [99 if long_list[i] == '0' else short_list[long_list[:i].count('1')]
     for i in range(len(long_list))]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      相关资源
      最近更新 更多