【问题标题】:How to club certain parts of list: Python如何组合列表的某些部分:Python
【发布时间】:2018-08-17 05:59:59
【问题描述】:

我有一个字符串示例列表:

my_list = ['hello','this','is','a','sample','list', 'thanks', 'for', 'help']

我想将每三个元素组合在一起,例如:

new_list = ['hello this is', 'a sample list', 'thanks for help']

【问题讨论】:

    标签: python python-3.x list string-concatenation


    【解决方案1】:

    只需拆分成块并加入:

    [' '.join(my_list[i:i+3]) for i in range(0, len(my_list), 3)]
    

    【讨论】:

      【解决方案2】:

      您可以通过使用一个步骤进行迭代来解决此问题,在本例中为 3 个步骤,并在每个步骤下添加单独的字符串,即my_list[i]my_list[i+1]my_list[i+2 ]。请注意,您需要在每个第一个和第二个字符串之后添加一个空格。这段代码就是这样做的:

      new_list = []
      for i in range(0, len(my_list), 3):
          if i + 2 < len(my_list):
              new_list.append(my_list[i] + ' ' + my_list[i+1] + ' ' + my_list[i+2])
      print(new_list)
      

      输出如预期:

      ['hello this is', 'a sample list', 'thanks for help']
      

      【讨论】:

        【解决方案3】:

        使用itertools 的几个解决方案是可能的。

        使用groupby

        [' '.join(x[1] for x in g) for _, g in groupby(enumerate(my_list), lambda x: x[0] // 3)]
        

        使用teezip_longest

        a, b = tee(my_list)
        next(b)
        b, c = tee(b)
        next(c)
        [' '.join(items) for items in zip_longest(a, b, c, fillvalue='')]
        

        只使用zip_longest:

        [' '.join(g) for g in zip_longest(*[iter(my_list)] * 3, fillvalue='')]
        

        最后两个改编自文档中的pairwisegrouperrecipes。如果不是 3 个单词的倍数,则只有第一个选项不会在最后一组的末尾添加额外的空格。

        【讨论】:

          【解决方案4】:

          选项 1:如果my_list 长度不能被 3 整除,此解决方案会丢弃元素

          输入字符串:['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']

          [" ".join(i) for i in zip(*[iter(my_list)]*3)]
          

          结果:['hello this is', 'a sample list', 'thanks for help']

          python iter 技巧的工作原理:How does zip(*[iter(s)]*n) work in Python?

          选项 2:使用 zip_longest 保留额外元素

          输入字符串:['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']

          [" ".join(i) for i in zip_longest(*[iter(my_list)]*3, fillvalue='')]
          

          结果:['hello this is', 'a sample list', 'thanks for help', 'foo ']

          【讨论】:

          • 注意,如果列表的长度不能被 3 整除,这种方法会在最后省略任何内容。这可能是也可能不是问题,但可能值得注意
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-16
          • 2017-07-11
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多