我研究过无数的其他问题,但似乎没有一个对我有用。我也尝试过很多不同的事情,但我不明白我需要做什么。我不知道还能做什么。
清单:
split_me = ['this', 'is', 'my', 'list', '--', 'and', 'thats', 'what', 'it', 'is!', '--', 'Please', 'split', 'me', 'up.']
我需要:
所以就变成这样:
this=['this', 'is', 'my', 'list']
and=['and', 'thats', 'what', 'it', 'is!']
please=['Please', 'split', 'me', 'up.']
目前的尝试(正在进行中):
for value in split_me:
if firstrun:
newlist=list(value)
firstrun=False
continue
if value == "--":
#restart? set firstrun to false?
firstrun=False
continue
else:
newlist.append(value)
print(newlist)
发布于 2017-11-03 10:02:31
虽然我不得不改变字词来解决保留字的问题,但这或多或少是可行的。(调用变量‘和’是个坏主意)。
split_me = ['This', 'is', 'my', 'list', '--', 'And', 'thats', 'what', 'it', 'is!', '--', 'Please', 'split', 'me', 'up.']
retval = []
actlist = []
for e in split_me:
if (e == '--'):
retval.append(actlist)
actlist = []
continue
actlist.append(e)
if len(actlist) != 0:
retval.append(actlist)
for l in retval:
name = l[0]
cmd = name + " = " + str(l)
exec( cmd )
print This
print And
print Please
发布于 2017-11-03 10:03:29
利用itertools.groupby()
dash = "--"
phrases = [list(y) for x, y in groupby(split_me, lambda z: z == dash) if not x]
初始化一个dict并将每个列表映射到该列表中的第一个单词:
myDict = {}
for phrase in phrases:
myDict[phrase[0].lower()] = phrase
将产生以下结果:
{'this': ['this', 'is', 'my', 'list]
'and': ['and', 'thats', 'what', 'it', 'is!']
'please': ['Please', 'split', 'me', 'up.'] }
发布于 2017-11-03 10:21:39
这实际上将创建名为全局变量的全局变量,该变量的命名方式与您希望它们的命名方式相同。不幸的是,它不适用于Python关键字,例如and
,因此,我要用'And'
替换'and'
。
split_me = ['this', 'is', 'my', 'list', '--', 'And', 'thats', 'what', 'it',
'is!', '--', 'Please', 'split', 'me', 'up.']
new = True
while split_me:
current = split_me.pop(0)
if current == '--':
new = True
continue
if new:
globals()[current] = [current]
newname = current
new = False
continue
globals()[newname].append(current)
基于@Mangohero1 1的一种更优雅的方法是:
from itertools import groupby
dash = '--'
phrases = [list(y) for x, y in groupby(split_me, lambda z: z == dash) if not x]
for l in phrases:
if not l:
continue
globals()[l[0]] = l
https://stackoverflow.com/questions/47101607
复制