在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",并且为了保持一致性,用一些数字(比如 99("替换"long_list中的"0"。
我可以通过一个令人痛苦的 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
转到迭代器并使用列表推导从那里获取每个'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( 时间复杂度,其中 n 是long_list
中元素的数量。请注意,这对于所有类型的可迭代对象都是一样的,long_list
和short_list
可能是生成器,最终结果是相同的。
如果您在更改short_list
时没有问题,则可以使用列表推导式尝试以下操作:
[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))]