【问题标题】:Python LPTHW: What is this loop statement doing in his functionPython LPTHW:这个循环语句在他的函数中做了什么
【发布时间】:2015-04-13 21:07:21
【问题描述】:

我正在关注“Learn Python The Hard Way”一书,但我不明白练习 39 中的这个函数发生了什么。

def new(num_buckets=256): #So the function is made and its named "new" and the argument inside is
    """Initializes a Map with the given number of buckets."""
    aMap = [] #then it creates an empty list and names it aMap 
    for i in range(0, num_buckets): #This loop is created named i and it is ranging from 0-255.
        aMap.append([]) #then it adds a list inside our aMap variable.
    return aMap

我不知道“for i in range(0,num_bucketss) 在这里做什么。它在做什么 append 命令?

【问题讨论】:

  • 加一行print(i),想想每次aMap如何变化。另外,想想变量名num_buckets...
  • 我试过添加打印命令。它给了我这个:“
  • 好吧,那么您肯定做错了某事——您使用了我建议的确切打印语句吗?在学习过程中,能够明确循环是很有帮助的。

标签: python function loops


【解决方案1】:

它在aMap 中添加与num_buckets 指定的一样多的空列表。所以,如果num_buckets = 5aMap 将是一个包含 5 个空列表的列表。

至于为什么这样做,我们需要更多的上下文。

编辑:

看到context,它这样做是为了为哈希图创建一些空桶。您可以在此处阅读有关哈希图如何使用存储桶的更多信息: What is meant by number of buckets in the HashMap?

【讨论】:

  • 用于创建我们自己的字典模块:learnpythonthehardway.org/book/ex39.html。所以如果它是num_buckets = 3。它基本上是在一个列表中制作3个列表?喜欢 [ [],[],[] ] ?
  • @Lia:正确,它会变成[[],[],[]]。看到上下文,它这样做是因为字典使用多个buckets 进行操作。有关详细信息,请参阅编辑。
  • 好的,我还有一个问题。 “for i in range(0, num_buckets): 如何应用于 aMap.append([])?我认为由于“for 循环”被命名为“i”,因此它必须应用于 aMap.append() 中的某个位置让它创建 255 个列表,但我认为 aMap.append([]) 与循环无关
  • i 是这里的循环计数器。没有要求您必须在循环中使用计数器。例如:for i in range(1, 100): print "Hello World!"
  • 啊,好的,我明白了。谢谢您的帮助。这一直困扰着我一整天,我不明白为什么。这本书没有像我想要的那样深入循环。您的 Hello World 示例非常有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
相关资源
最近更新 更多