【问题标题】:Python: Split list in arrayPython:数组中的拆分列表
【发布时间】:2010-12-13 18:16:05
【问题描述】:

刚从python开始,知道的足以知道我一无所知。我想找到将列表拆分为字典列表的替代方法。示例列表:

data = ['**adjective:**', 'nice', 'kind', 'fine',
        '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', 
        '**adverb:**', 'well', 'nicely', 'fine', 'right', 'okay'] 

我可以得到:

[{'**adjective**': ('nice', 'kind', 'fine'),
 '**noun**': ('benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'),
 '**adverb**': ('well', 'nicely', 'fine', 'right', 'okay')}] 

【问题讨论】:

  • 不可能获得像您发布的第二个那样的列表/字典结构。它必须更像这样:{'adjective': ['nice', 'kind', 'fine'], 'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'], 'adverb': 'well', 'nicely', 'fine', 'right', 'okay']}
  • 列表是大多数语言所说的数组,PHP 所说的数组是数组和字典的结合。 Python 中没有 {key1: val1, val2, val3} 这样的东西。
  • 您的输出不太有效。你想要 {'adjective': ['nice', 'kind'], 'noun': ['benefit', profit',...]} 吗?

标签: python list dictionary split


【解决方案1】:

这可能与您的要求很接近:

d = collections.defaultdict(list)
for s in data:
    if s.endswith(":"):
        key = s[:-1]
    else:
        d[key].append(s)
print d
# defaultdict(<type 'list'>, 
#     {'adjective': ['nice', 'kind', 'fine'], 
#      'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'], 
#      'adverb': ['well', 'nicely', 'fine', 'right', 'okay']})

编辑:只是为了好玩,灵感来自 SilentGhost 的答案的另一种两条线:

g = (list(v) for k, v in itertools.groupby(data, lambda x: x.endswith(':')))
d = dict((k[-1].rstrip(":"), v) for k, v in itertools.izip(g, g))

【讨论】:

    【解决方案2】:
    >>> data = ['adjective:', 'nice', 'kind', 'fine', 'noun:', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', 'adverb:', 'well', 'nicely', 'fine', 'right', 'okay']
    >>> from itertools import groupby
    >>> dic = {}
    >>> for i, j in groupby(data, key=lambda x: x.endswith(':')):
        if i:
            key = next(j).rstrip(':')
            continue
        dic[key] = list(j)
    
    >>> dic
    {'adjective': ['nice', 'kind', 'fine'], 'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'], 'adverb': ['well', 'nicely', 'fine', 'right', 'okay']}
    

    【讨论】:

    • 我认为应该是rstrip() 而不是lstrip(),对吧?如果输入列表中有两个中间没有值的键,这会产生奇怪的结果,但要求实际上不够明确。
    • @kevpie、@user、@Sven:谢谢,已修复。左右,其实我不得不做出选择,做出了错误的选择。
    【解决方案3】:

    下面的代码将为您提供一个字典,其中每个单词都有一个条目,后面有一个冒号。

    data = ['adjective:', 'nice', 'kind', 'fine', 'noun:', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', 'adverb:', 'well', 'nicely', 'fine', 'right', 'okay']
    result = {}
    key = None
    for item in data:
     if item.endswith(":"):
      key = item[:-1]
      result[key] = []
      continue
     result[key].append(item)
    

    【讨论】:

      【解决方案4】:

      如果后面有没有列表元素的键? , 我想。 所以我在前面添加了“nada:”,在中间添加了“nothing:”,在名为 data 的列表末尾添加了“oops:”。

      那么,在这些条件下, 带有 groupy 的代码 1(如下)似乎给出了完全错误的结果, 带有 defaultdict 的代码 2 给出的结果是键 'nada:' 、 'nothing:' 和 'oops:' 不存在。 它们的速度也不如最简单的解决方案(代码 3:Cameron,user506710)

      我有一个想法 => 代码 4 和 5。 结果还可以,执行速度更快。

      from time import clock
      
      data = ['nada:',    # <<<=============
          'adjective:',
          'nice', 'kind', 'fine',
          'noun:',
          'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal',
          'nothing:', # <<<=============
          'adverb:',
          'well', 'nicely', 'fine', 'right', 'okay',
          'oops:'     # <<<=============
          ]
      
      #------------------------------------------------------------
      from itertools import groupby
      
      te = clock()
      dic1 = {}
      for i, j in groupby(data, key=lambda x: x.endswith(':')):
          if i:
              key = next(j).rstrip(':')
              continue
          dic1[key] = list(j)
      print clock()-te,'    groupby'
      print dic1,'\n'
      
      #------------------------------------------------------------
      from collections import defaultdict
      te = clock()
      dic2 = defaultdict(list)
      for s in data:
          if s.endswith(":"):
              key = s[:-1]
          else:
              dic2[key].append(s)
      print clock()-te,'   defaultdict'
      print dic2,'\n\n==================='
      
      #=============================================================
      te = clock()
      dic4 = {}
      for x in data:
          if x[-1] == ':' :
              start = x.rstrip(':')
              dic4[start] = []
          else:
          dic4[start].append(x)
      print clock() - te
      print dic4,'\n'
      
      #------------------------------------------------------------
      te = clock()
      dic3 = {}
      der = len(data)
      for i,y in enumerate(data[::-1]):
          if y[-1]==':':
              dic3[y[0:-1]] = data[len(data)-i:der]
              der = len(data)-i-1
      print clock()-te
      print dic3,'\n'
      
          #------------------------------------------------------------
      te = clock()
      dic5 = {}
      der = len(data)
      for i in xrange(der-1,-1,-1):
          if data[i][-1]==':':
              dic5[data[i][0:-1]] = data[i+1:der]
              der = i
      print clock() - te
      print dic5
      
      print '\ndic3==dic4==dic5 is',dic3==dic4==dic5
      

      【讨论】:

        【解决方案5】:

        如果您假设 inner 是单词列表,您可以将其作为代码

        data = ['adjective:', 'nice', 'kind', 'fine', 'noun:', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', 'adverb:', 'well', 'nicely', 'fine', 'right', 'okay']
        
        dict = {}
        
        for x in data:
        
            if x[-1] == ':' :
        
               start = x.rstrip(':')
        
               dict[start] = []
        
            else:
        
               dict[start].append(x)
        
        print dict
        

        这将打印以下字典

        {'adjective': ['nice', 'kind', 'fine'], 'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'], 'adverb': ['well', 'nicely', 'fine', 'right', 'okay']}
        

        【讨论】:

          猜你喜欢
          • 2015-12-01
          • 2020-05-12
          • 1970-01-01
          • 2016-01-08
          • 2019-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多