python - 向字符串列表添加超过 1 个后缀,序列不受影响
问题描述
我有一个字符串列表:
string = ["banana", "apple", "cat", dog"]
和后缀列表(项目数不固定,可以是 1、2 或更多):
suffix = ["0422", "1932"]
我的愿望输出(顺序很重要,应该与原始列表相同):
output = ["banana", "banana0422", "banana1932", "apple", "apple0422", "apple1932", "cat", "cat0422", "cat1932", "dog", "dog0422", "dog1932"]
通读许多堆栈溢出帖子,但其中大多数只是添加 1 个后缀,但在我的情况下,可能有 2 个甚至更多后缀。尝试了 itertools.product 但仍然不是我想要的。
寻找聪明有效的东西。谢谢。
解决方案
您可以使用List-comprehension,将带有空字符串的列表添加到suffix
列表中
>>> [item+suff for item in string for suff in ['']+suffix]
['banana', 'banana0422', 'banana1932', 'apple', 'apple0422', 'apple1932', 'cat', 'cat0422', 'cat1932', 'dog', 'dog0422', 'dog1932']
推荐阅读
- python-3.x - 如何解决 GET 参数中的 API 密钥错误?
- python - 如何使用 pl/python 3 在 Windows 服务器上运行多进程?
- python - 在整个程序中访问金字塔设置
- solr - 为什么 Solr 搜索查询会返回这么大的摘录?
- python - 在异步循环中定义一次变量?Python 请求
- python - PlotLy:无法在子图上绘制烛台图
- sql - 如何估计 Azure SQL PiTR 备份的存储大小
- go - 如何根据go中的日期列对csv数据进行排序
- git - 在 Rebase 期间升级 git 版本
- javascript - 提高 contenteditable 打字性能