python - 在预定义的位置将值从一个列表插入另一个列表

时间:2017-02-09 14:54:03

标签: python list for-loop list-comprehension

在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]

3 个答案:

答案 0 :(得分:8)

short_list转换为迭代器,并为每个'1'使用list comprehension get value,否则使用固定值:

>>> 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_list1上的long_list具有相同数量或更多元素时,这显然有效。以上 O(n)时间复杂度,其中 n long_list中元素的数量。请注意,对于所有类型的迭代,这都是相同的,long_listshort_list可能是生成器,最终结果是相同的。

答案 1 :(得分:3)

如果您在更改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]

答案 2 :(得分:0)

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

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