首页 > 解决方案 > 向字符串列表添加超过 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 但仍然不是我想要的。

寻找聪明有效的东西。谢谢。

标签: pythonstringlistsortingsuffix

解决方案


您可以使用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']

推荐阅读