将多个后缀添加到字符串列表中,顺序不受影响

Add more than 1 Suffix to a list of Strings, with the sequence not affected

我有一个字符串列表:

string = ["banana", "apple", "cat", dog"]

和后缀列表(项数不固定,可以是1、2或更多):

suffix = ["0422", "1932"]

我的愿望输出(顺序很重要,应该和原来的列表一样):

output = ["banana", "banana0422", "banana1932", "apple", "apple0422", "apple1932", "cat", "cat0422", "cat1932", "dog", "dog0422", "dog1932"]

通读了许多堆栈溢出 post,但其中大部分都是关于仅添加 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']

我猜你的问题不是方法,而是添加了无后缀选项,为此在其他后缀前面添加一个空字符串

suffixes = ["0422", "1932"]
[''] + suffixes # ['', '0422', '1932']

您需要 2 个 for 循环,使用经典语法或在列表理解中

string = ["banana", "apple", "cat", "dog"]
suffixes = ["0422", "1932"]
result = [word + suffix for word in string for suffix in [''] + suffixes]

也适用于 itertools.product

from itertools import product
result = list(map("".join, product(string, [''] + suffixes)))

您可以将 itertools.productstr.join 一起使用。

import itertools

fruits = ["banana", "apple"]
suffixes = ["X", "Y"]
output = itertools.product(fruits, [""] + suffixes)  # add empty string to have fruit without suffix
output = map("".join ,output)
output = list(output)
print(output)  # prints ['banana', 'bananaX', 'bananaY', 'apple', 'appleX', 'appleY']

您甚至可以为此创建函数

import itertools

def combine(input, suffixes):
    """Adds suffix from suffixes list into each element from input list"""
    if "" not in suffixes:
        suffixes = [""] + suffixes
    output = itertools.product(input, suffixes)
    output = map("".join ,output)
    output = list(output)
    return output