如何在Python IDLE中编写和运行多个代码?
你想知道怎么在IDLE里运行下面的代码,对吧?我现在在课程中遇到了一些困难,找不到解释。我知道怎么在IDLE里运行一个“def”或者一段代码,只需要按F5,然后在命令行里输入,比如说hash_string('udacity', 3),再按“Enter”,就能看到结果。但是如果代码有很多行,这样就不行了。为了更深入地理解,我想在Python在线教程里运行这段代码,前提是它能在IDLE里运行,或者反过来也可以。
另外,我还想知道,为什么输入#print hashtable_get_bucket(table, "Zoe")会得到这个结果:#>>> [['Bill', 17], ['Zoe', 14]]。为什么列表里会出现'Bill'和17?
# Define a procedure, hashtable_get_bucket,
# that takes two inputs - a hashtable, and
# a keyword, and returns the bucket where the
# keyword could occur.
def hashtable_get_bucket(htable,keyword):
return htable[hash_string(keyword,len(htable))]
def hash_string(keyword,buckets):
out = 0
for s in keyword:
out = (out + ord(s)) % buckets
return out
def make_hashtable(nbuckets):
table = []
for unused in range(0,nbuckets):
table.append([])
return table
#table = [[['Francis', 13], ['Ellis', 11]], [], [['Bill', 17],
#['Zoe', 14]], [['Coach', 4]], [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]]
#print hashtable_get_bucket(table, "Zoe")
#>>> [['Bill', 17], ['Zoe', 14]]
#print hashtable_get_bucket(table, "Brick")
#>>> []
#print hashtable_get_bucket(table, "Lilith")
#>>> [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]
谢谢你花时间阅读这篇帖子,也感谢你的建议!
1 个回答
0
首先回答你的最后一个问题:table
是一个三重列表,也就是说它是一个包含列表的列表,而这些列表里面又可以有列表。比如其中一个列表是 [['Bill', 17], ['Zoe', 14]]
。因为 hash_string
返回的是一个索引,它从 table
中取出一个列表,而这个列表正好是包含 Bill 和 Zoe 的那个。
另外,如果你想在 IDLE 中运行多个函数,你需要创建一个新的函数(比如 def my_assignment
或其他名称),然后在这个新函数里调用其他的函数。
希望这些对你有帮助。