Python:在数组中拆分列表

时间:2010-12-13 18:16:05

标签: python list dictionary split

刚开始使用python并且知道得知道我什么都不知道。我想找到将列表拆分为dicts列表的替代方法。示例列表:

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')}] 

5 个答案:

答案 0 :(得分:10)

这可能与您提出的要求非常接近:

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

答案 1 :(得分:5)

>>> 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']}

答案 2 :(得分:1)

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

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)

答案 3 :(得分:0)

如果你假设内部是单词列表,你可以将其作为代码

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']}

答案 4 :(得分:0)

如果有没有列表元素的键呢? , 我想。 所以我在前面添加'nada:',在中间添加'nothing:',在名单数据列表的末尾添加'oops:'。

然后,在这些条件下, 带有groupy的代码1(如下所示)似乎给出了完全错误的结果, 带有defaultdict的代码2给出了一个结果,其中缺少键'nada:','nothing:'和'oops:'。 它们的速度也比最简单的解决方案快(代码3:Cameron,user506710)

我有个主意=&gt;代码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