烦人的Python循环错误?
我已经尝试解决这个问题一段时间了,但似乎一直没有找到问题所在。
listy2=['fun','super','Stop']
listy=['great','life','Stop','toys','nothing','Stop']
listpool=[listy,listy2]
current=[]
total=[]
nested=True
for i in listpool:
for line in enumerate(i):
if (line[0]==0):
current.append(line[1])
#skipping first line
continue
if (line[1].strip()!="") and (nested==True):
current.append(line[1])
nested=False
continue
if (line[1].strip()=="Stop"):
nested=True
continue
total.append(current)
#current[:] = []
print total
这个程序应该输出一个列表的列表。 [[列表的第一个元素,嵌套的东西],[列表的第一个元素,嵌套的东西]]
嵌套的东西就像是:
hello
blah blah
Stop
在这个例子中,嵌套的东西是hello。 这个列表可以有多个嵌套的东西。
cool
blah blah
Stop
good
blah blah
Stop
在这个例子中,嵌套的东西是cool和good,(你可以看出来,中间的东西并不重要)
在我的代码中,它应该输出
[['fun','super'],['great','life','toys']]
但是实际上并没有。
抱歉,如果我不能很好地解释这个问题,因为英语不是我的母语,但我正在逐渐适应。如果你有任何问题或评论,请在这里留言。抱歉如果我做了什么愚蠢的事情。如果你能解释我的错误,那就太好了,但这并不是必要的。 谢谢。
4 个回答
1
我把处理单个列表的代码放进了一个函数里:我觉得这样写代码更简单,也更容易测试和理解。我发现给这个函数起个好名字有点难,因为我其实不太明白这段代码的具体目的,但看起来它能做到你想要的事情。
def stop_words(words):
# Have we ever seen the word 'Stop'?
found_stop = False
# Was the last word seen 'Stop'?
last_stop = False
for word in words:
if word == 'Stop':
found_stop = last_stop = True
continue
if not found_stop or last_stop:
yield word
last_stop = False
print [list(stop_words(words)) for words in [listy, listy2]]
你在用英语表达你想让代码做什么时遇到了困难,这让我觉得你在用代码表达时也会有类似的问题。我本来会说,这段代码应该提取出在第一个“Stop”之前的每一个单词,以及在“Stop”之后的单词。
2
你创建了一个 当前 列表,并在主循环的每次迭代中往里面添加内容。其实你可能更想在每次迭代时都创建一个新的 当前
列表:
for i in listpool:
current = []
...
total.append(current)
1
我不太明白你在这里想做的所有事情,但最简单的回答是,你在外层循环的每次迭代之间没有清空“当前”列表。
你可以试试这样做:
listy2=['fun','super','Stop']
listy=['great','life','Stop','toys','nothing','Stop']
listpool=[listy,listy2]
total=[]
nested=True
for i in listpool:
current=[]
for line in enumerate(i):
if (line[0]==0):
current.append(line[1])
#skipping first line
continue
if (line[1].strip()!="") and (nested==True):
current.append(line[1])
nested=False
continue
if (line[1].strip()=="Stop"):
nested=True
continue
total.append(current)
print total
这样写(稍微)更符合Python的习惯:
listy=['great','life','Stop','toys','nothing','Stop']
listy2=['fun','super','Stop']
listpool=[listy,listy2]
total=[]
for i in listpool:
nested=True
current=[]
for (n, line) in enumerate(i):
if (n==0):
current.append(line) #skipping first line
elif nested and line.strip():
current.append(line)
nested=False
elif line.strip()=="Stop":
nested=True
total.append(current)
print total