python - 用多个元素替换列表中的元素

标签 python python-3.x

<分区>

我想用多个元素替换列表中的一个元素。例如,我有列表 a = ['b', 'c'] 并想用 'd', 'e' 替换 'b' 这会给我列表 a = ['d', 'e', 'c']

我有以下代码:a = [??? if item == 'b' else item for item in a].我该如何进行?我很乐意保持列表理解,因为这似乎比 a.extend(('b', 'c')) 更合适,例如。

最佳答案

另一种选择是编写一个生成器函数:

def replace_item(the_list):
    for item in the_list:
        if item == 'b':
            yield 'd'
            yield 'e'
        else:
            yield item
>>> list(replace_item(['a', 'b']))
['a', 'd', 'e']

关于python - 用多个元素替换列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356271/

相关文章:

python - 如何在 python 中将值插入到列表中......有一些额外的条件

python - 如何使用 numpy 创建单位矩阵

python - 为 Yocto 创建配方时,python3 中没有名为 'datetime' 的模块,但 python2.7 中存在日期时间

python - 如何让 ChatGPT API 做出与网页版类似的响应?

python - 基本 HTTPServer 卡在 "socket.readinto : return self._sock.recv_into(b)"

python - 为每组连续增加的日期添加行号列

python - 将 Jupyter Notebook 转换为 PDF 时如何渲染图像?

python - 如何从 Azure 机器学习工作室中的 R 或 Python 脚本读取本地文件?

python - 这种切片行为是否已定义?

python - 如何将以下 Python 字符串拆分为字符串列表?