【问题标题】:Combine elements of lists if some condition如果某些条件,合并列表的元素
【发布时间】:2015-02-10 08:13:46
【问题描述】:

我如何组合列表的元素如果满足某些条件。

我看过关于组合列表元素的帖子,但不是在某些条件下。

假设我有一个包含单词列表的列表:

words = [
    ['this','that!','riff','raff'],
    ['hip','hop!','flip!','flop'],
    ['humpty','dumpty!','professor!','grumpy!']
]

如何只组合那些包含! 的元素?

例如,输出如下所示:

[['this', 'that!', 'riff', 'raff'],
 ['hip', 'hop!, flip!', 'flop'],  # 1,2 are now combined
 ['humpty', 'dumpty!, professor!, grumpy!']]   # 1,2,3 are now combined

我试过这个:

for word in words:
    word = ', '.join(i for i in word if re.search('!',str(i)))
    print word

但是得到了:

that!
hop!, flip!
dumpty!, professor!, grumpy!

谢谢。

【问题讨论】:

  • 我无法分辨您想要的输出和原始单词列表之间的区别......
  • 如果包含!的元素是连续的,您是否只想合并它们? ['a!', 'b', 'c!'] 会发生什么?
  • @Cyber​​ 一些字符串像'hop!', 'flip!' -> 'hop!, flip!'
  • @interjay,仅当它们连续出现时。
  • @PadraicCunningham 有细微的差别。

标签: python list python-2.7


【解决方案1】:

使用itertools.groupby:

>>> from itertools import groupby
>>> out = []
>>> for lst in words:
    d = []
    for k, g in groupby(lst, lambda x: '!' in x):
        if k:
            d.append(', '.join(g))
        else:
            d.extend(g)
    out.append(d)
...     
>>> out
[['this', 'that!', 'riff', 'raff'],
 ['hip', 'hop!, flip!', 'flop'],
 ['humpty', 'dumpty!, professor!, grumpy!']]

【讨论】:

    【解决方案2】:

    这是我的解决方案:

    words = [
        ['this','that!','riff','raff'],
        ['hip','hop!','flip!','flop'],
        ['humpty','dumpty!','professor!','grumpy!']
    ]
    
    output = []
    for wl in words:
        out_wl = []
        bang_wl = []
        for w in wl:
            if '!' in w:
                bang_wl.append(w)
            else:
                if bang_wl:
                    out_wl.append(','.join(bang_wl))
                    bang_wl = []
                out_wl.append(w)
        if bang_wl:
            out_wl.append(','.join(bang_wl))
        output.append(out_wl)
    
    print output
    

    输出:

    [['this', 'that!', 'riff', 'raff'], ['hip', 'hop!,flip!', 'flop'], ['humpty', 'dumpty!,professor!,grumpy!']]
    

    bang_wl! 累加单词,直到遇到不包含! 的单词。此时,它将joins bang_wl 中的单词添加到output_wl 列表中。

    【讨论】:

      【解决方案3】:
      result = []
      
      for sub_lst in words:
          result.append([])
          temp = ""
          for ele in sub_lst:
              if not temp and not "!" in ele:
                  result[-1].append(ele)
              elif temp and not "!" in ele:
                  result[-1].append(temp)
                  result[-1].append(ele)
                  temp = ""
              else:
                  temp += "," + ele if temp else ele
          if temp:
              result[-1].append(temp)
       [['this', 'that!', 'riff', 'raff'], ['humpty', 'dumpty!,professor!,grumpy!'], ['hip', 'hop!,flip!', 'flop']]
      

      如果您希望连接所有带有! 的单词,包括由不包含! 的单词分隔的单词,即['humpty', 'dumpty!', 'professor!', 'grumpy!',"foo","bar!"] 将变为 ['humpty', 'foo', 'dumpty!,professor!,grumpy!,bar!']:

      result = []
      for sub_l in words:
          result.append([])
          temp = ""
          for word in sub_l:
              if "!" in word:
                  temp += "," + word if temp else word
              else:
                  result[-1].append(word)
          result[-1].append(temp)
      

      一些时间显示@vikramls 效率最高,而 itertools 解决方案效率最低。:

      In [31]: %%timeit
         ....: result = []
         ....: for sub_lst in words:
         ....:     result.append([])
         ....:     temp = ""
         ....:     for ele in sub_lst:
         ....:         if not temp and not "!" in ele:
         ....:             result[-1].append(ele)
         ....:         elif temp and not "!" in ele:
         ....:             result[-1].append(temp)
         ....:             result[-1].append(ele)
         ....:             temp = ""
         ....:         else:
         ....:             temp += "," + ele if temp else ele
         ....:     if temp:
         ....:         result[-1].append(temp)
         ....: 
      100000 loops, best of 3: 16 µs per loop
      
      In [32]: %%timeit
      output = []
      for wl in words:
          out_wl = []
          bang_wl = []
          for w in wl:
              if '!' in w:                   
                  bang_wl.append(w)
              else:                        
                  if bang_wl:
                      out_wl.append(','.join(bang_wl))
                      bang_wl = []
                  out_wl.append(w)
          if bang_wl:                               
              out_wl.append(','.join(bang_wl))
          output.append(out_wl)
         ....: 
      100000 loops, best of 3: 15.2 µs per loop
      
      In [33]: %%timeit
      out = []
      >>> for lst in words:
          d = []
          for k, g in groupby(lst, lambda x: '!' in x):
              if k:
                  d.append(', '.join(g))
              else:                     
                  d.extend(g)
          out.append(d)
         ....: 
      10000 loops, best of 3: 48.1 µs per loop
      

      如果您只想要以! 结尾的单词:

      In [34]: %%timeit
      result = []
      for sub_lst in words:
          result.append([])
          temp = ""                              
          for ele in sub_lst:
              if not temp and not ele[-1] == "!":
                  result[-1].append(ele)
              elif temp and not ele[-1] == "!":
                  result[-1].append(temp)
                  result[-1].append(ele)
                  temp = ""
              else:               
                  temp += "," + ele if temp else ele
          if temp:                            
              result[-1].append(temp)
         ....: 
      100000 loops, best of 3: 17 µs per loop
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 2014-04-12
        • 1970-01-01
        • 2018-04-11
        相关资源
        最近更新 更多