Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在数组中拆分列表_Python_List_Dictionary_Split - Fatal编程技术网

Python:在数组中拆分列表

Python:在数组中拆分列表,python,list,dictionary,split,Python,List,Dictionary,Split,从python开始,我知道我什么都不知道。我想找到另一种方法,将一个列表拆分为一个目录列表。示例列表: data = ['**adjective:**', 'nice', 'kind', 'fine', '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', '**adverb:**', 'well', 'nicely', 'fine', 'right',

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

这可能与您提出的问题非常接近:

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

如果您假设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']}

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

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)

如果有键后面没有列表元素,我想。 所以我在前面加了一个“NADA:”,中间没有“ON:”,“OOP:”在命名为“DATA”的列表的末尾。 那么在这种情况下,, 带有groupy的代码1(在下面)似乎给出了一个完全错误的结果, 带有defaultdict的代码2给出了一个缺少键“nada:”、“nothing:”和“oops:”的结果。 它们也没有最简单的解决方案快(代码3:Cameron,用户506710)

我有一个想法=>代码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
从时间导入时钟

data=['nada:',#不可能得到像你发布的第二个那样的列表/目录结构。它必须更像这样:
{'sapple':['nice'、'kind'、'fine']、'noon':['benefit'、'profit'、'advance'、'avail'、'fulf'、'use'、'weal']、'副词:'well'、'snely'、'snely'、'right'、'ok']]
列表是大多数语言所称的数组,PHP所称的数组是数组和dict的组合。Python中没有像
{key1:val1,val2,val3}
这样的东西。您的输出不是很有效。你想要{‘形容词’:['nice','kind'],'noon':['benefit',profect',profect',…]}吗?我想应该是
rstrip()
而不是
lstrip()
,对吗?如果输入列表中有两个键之间没有值,但要求不够明确,则会产生奇怪的结果。@kevpie,@user,@Sven:谢谢,修复了。事实上,从左到右,我不得不做出一个错误的选择。
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)
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