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

2024-03-29 10:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

一个短列表的长度等于长列表中“1”的数目,如下所示:

short_list = [8,7,6,5]

我该如何创建一个新的列表,将短列表中的值“插入”到长列表中的每个索引中,其中有一个“1”,并且为了一致性起见,将长列表中的“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]

Tags: 方法in列表newforrange数字long
3条回答

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_listlong_list上的1具有相同数量或更多元素时,这种方法才有效。上面有O(n)时间复杂度,其中nlong_list中元素的数量。请注意,对于所有类型的iterable,这都是一样的,long_listshort_list可能是生成器,最终结果也是一样的。你知道吗

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

不是说这是最好的方法,而是不需要新的变量。你知道吗

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

相关问题 更多 >