python - 根据值拼接列表
问题描述
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。
解决方案
我能找到的最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))
它应该按预期工作。
推荐阅读
- php - 图像(Blob)在浏览器中仅显示一次
- javascript - 从 componentDidMount 方法访问道具状态给出未定义
- python - Python 请求正文自动添加单引号
- node.js - Chrome 启动器以 UnhandledPromiseRejectionWarning 退出
- json.net - 如何使用 json.net 将此 JWT 反序列化为一个类
- dart - 使用 Flutter 在运行时更新资产文件内容
- r - 如何填写每月时间序列数据的缺失行?
- javascript - 我在网上找到的这个切换脚本仅适用于父 ID,但不适用于父母的孩子
- docusignapi - USER_LACKS_MEMBERSHIP Docusign Nodejs
- macos - 在通过自制软件安装的 macos 上访问 Rabbit MQ UI 时出错