【问题标题】:Add more than 1 Suffix to a list of Strings, with the sequence not affected向字符串列表添加超过 1 个后缀,序列不受影响
【发布时间】:2021-09-15 14:25:53
【问题描述】:

我有一个字符串列表:

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 但仍然不是我想要的。

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

【问题讨论】:

    标签: python string list sorting suffix


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      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)))
      

      【讨论】:

        【解决方案3】:

        您可以将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
        

        【讨论】:

          猜你喜欢
          • 2011-01-13
          • 1970-01-01
          • 2021-03-25
          • 2011-01-06
          • 2023-03-10
          • 2018-10-23
          • 2021-12-30
          • 2017-02-15
          • 2021-12-16
          相关资源
          最近更新 更多