python中,用list做栈出的一点小意外

heshang110 2007-10-18 03:36:15
参考书中用python做了一个简单的栈,可是输出结果为什么跟我想的预期的相差比较远?代码如下:def convert_parens(tokens):
stack = [[]]
for token in tokens:
if token == '(': # push
sublist = []
stack[-1].append(sublist)
stack.append(sublist)
elif token == ')': # pop
stack.pop()
else: # update top of stack
stack[-1].append(token)
return stack[0]

比如,我们这样调用:
>>> phrase = "( the cat ) ( sat ( on ( the mat ) ) )"
>>> convert_parens(phrase.split())
当把第一个the压栈了以后,栈内的情况是这样子的
[[['the']], ['the']]
压入第二个cat
[[['the', 'cat']], ['the', 'cat']]
最后成了
[[['the', 'cat'], ['sat', ['on', ['the', 'mat']]]], ['sat', ['on', ['the', 'mat']]], ['on', ['the', 'mat']], ['the', 'mat']]
我认为到所有的入栈操作都是在stack[-1].append(token)上进行的,可是为什么在stack[0]上也会总有入栈呢?谢谢指点!
...全文
226 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
meiZiNick 2008-05-01
  • 打赏
  • 举报
回复
好像没那么简单,呵呵.
UltraBejing 2008-04-30
  • 打赏
  • 举报
回复
以后需再关注,现在先帮你顶一下
heshang110 2007-10-20
  • 打赏
  • 举报
回复

def convert_parens(tokens):
stack = [[]]
for token in tokens:
if token == '( ': # push
sublist = []
stack[-1].append(sublist)
stack.append(sublist)
elif token == ') ': # pop
stack.pop()
else: # update top of stack
stack[-1].append(token)
return stack[0]

比如,我们这样调用:
> > > phrase = "( the cat ) ( sat ( on ( the mat ) ) )"
> > > convert_parens(phrase.split())
当把第一个the压栈了以后,栈内的情况是这样子的
[[[ 'the ']], [ 'the ']]
压入第二个cat
[[[ 'the ', 'cat ']], [ 'the ', 'cat ']]
最后成了
[[[ 'the ', 'cat '], [ 'sat ', [ 'on ', [ 'the ', 'mat ']]]], [ 'sat ', [ 'on ', [ 'the ', 'mat ']]], [ 'on ', [ 'the ', 'mat ']], [ 'the ', 'mat ']]
我认为到所有的入栈操作都是在stack[-1].append(token)上进行的,可是为什么在stack[0]上也会总有入栈呢?谢谢指点!
iambic 2007-10-20
  • 打赏
  • 举报
回复
晕,怎么没加缩进啊。我试着格式化了一下:

#!/usr/bin/python

def convert_parens(tokens):
stack = [[]]
for token in tokens:
if token == '( ': # push
sublist = []
stack[-1].append(sublist)
stack.append(sublist)
elif token == ') ': # pop
stack.pop()
else: # update top of stack
stack[-1].append(token)
return stack[0]


phrase = "( the cat ) ( sat ( on ( the mat ) ) )"
print convert_parens(phrase.split())


其次我不知道你这个栈是干什么的,你说你觉得得到的结果很奇怪,但我根本就不知道你期待的结果是什么。
对于这么多层嵌套的列表,你最好说下你的用意,至少说清楚你期待的结果。
iambic 2007-10-18
  • 打赏
  • 举报
回复
请把代码格式化后重发。

[code=Lang] ... your code ... [/code]
Lang处应为Python。

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧