我已经挖过无数其他问题,但似乎没有一个问题适合我。我也尝试了很多不同的东西,但我不明白我需要做什么。我不知道还能做什么。
列表:
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)
答案 0 :(得分:2)
这或多或少有效,虽然我不得不改变单词来解决保留字问题。 (糟糕的做法是调用变量'和')。
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
答案 1 :(得分:2)
利用itertools.groupby()
:
dash = "--"
phrases = [list(y) for x, y in groupby(split_me, lambda z: z == dash) if not x]
初始化一个字典并将每个列表映射到该列表中的第一个字:
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.'] }
答案 2 :(得分:2)
这实际上会创建以您希望它们命名的方式命名的全局变量。不幸的是,它不适用于and
之类的Python关键字,因此我将'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答案的更优雅的方法是:
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
答案 3 :(得分:1)
我会尝试一些ike
yourView.isHidden = !yourModel.isDisplayed