首页 > 解决方案 > 根据值拼接列表

问题描述

A 有一个值列表。我想从列表中删除特定值的出现,并在以前的位置插入多个值(该值恰好出现一次)。代码中的相同内容:

values = [1, 2, 3, 4, 5]
index = values.index(3)
values[index:index+1] = ['a', 'b', 'c']
# values == [1, 2, 'a', 'b', 'c', 4, 5]

我觉得它不太可读。有没有内置的方法可以做到这一点?如果没有,将其转换为函数的最佳方法是什么?

这是我想出的最好的代码:

def splice_by_value(iterable, to_remove, *to_insert):
    for item in iterable:
        if item == to_remove:
            for insert in to_insert:
                yield insert
        else:
            yield item

我正在使用 Python 3.7。

标签: pythonpython-3.xlist

解决方案


我能找到的最pythonic的方法是:

values = [1, 2, 3, 4, 5]
value = 3
replace = ['a', 'b', 'c']
def splice(values, value, replace):
    result = [replace if x == value else x for x in values]

您可以在其中选择要替换的值和替换的值。然而,这在非平面列表中。如果您需要它平坦,这应该会有所帮助(取自此处):

def flat_gen(x):
    def iselement(e):
        return not(isinstance(e, Iterable) and not isinstance(e, str))
    for el in x:
        if iselement(el):
            yield el
        else:
            for sub in flat_gen(el): yield sub

所以如果你使用类似的东西:

result_flat = list(flat_gen(result))

它应该按预期工作。


推荐阅读