【问题标题】:How does a for loop work in tuplesfor 循环如何在元组中工作
【发布时间】:2017-05-10 02:19:09
【问题描述】:

我是 python 新手,很难理解以下代码。如果有人可以给出解释,那就太好了。我有两个元组。具体来说,我无法理解 for 循环在这里是如何工作的。还有 weight_cost[index][0] 是什么意思。

ratios=[(3, 0.75), (2, 0.5333333333333333), (0, 0.5), (1, 0.5)]
weight cost=[(8, 4), (10, 5), (15, 8), (4, 3)]

best_combination = [0] * number
best_cost = 0
weight = 0
for index, ratio in ratios:
    if weight_cost[index][0] + weight <= capacity:
        weight += weight_cost[index][0]
        best_cost += weight_cost[index][1]
        best_combination[index] = 1

【问题讨论】:

  • 阅读python教程或python说明书是最好的方法。

标签: python loops for-loop tuples


【解决方案1】:

当您试图理解一段代码时,一个好的做法是删除不相关的部分,这样您就可以看到您关心的代码正在做什么。这通常称为MCVE

使用您的代码 sn-p,我们可以清理几项内容,以使我们感兴趣的行为更加清晰。

  1. 我们可以删除循环的内容,然后简单地打印值
  2. 我们可以删除不再使用的第二个元组和其他变量

留给我们:

ratios=[(3, 0.75), (2, 0.5333333333333333), (0, 0.5), (1, 0.5)]
for index, ratio in ratios:
  print('index: %s, ratio %s' % (index, ratio))

现在我们可以将其放入 REPL 并进行实验:

>>> ratios=[(3, 0.75), (2, 0.5333333333333333), (0, 0.5), (1, 0.5)]
>>> for index, ratio in ratios:
...   print('index: %s, ratio %s' % (index, ratio))
... 
index: 3, ratio 0.75
index: 2, ratio 0.5333333333333333
index: 0, ratio 0.5
index: 1, ratio 0.5

您现在可以清楚地看到它在做什么 - 按顺序遍历列表的每个元组,并将元组中的第一个和第二个值提取到 indexratio 变量中。

尝试对此进行试验 - 如果您制作大小为 1 或 3 的元组之一会发生什么?如果您只在循环中指定一个变量而不是两个变量会怎样?你能指定两个以上的变量吗?

【讨论】:

  • 非常感谢!
【解决方案2】:

for 循环遍历数组中的每个元组,将其零索引分配给index,并将其一索引分配给比率。

然后它检查 weight_cost 中的相应索引,这是一个元组,并检查该元组的零索引。这被添加到权重中,并且小于或等于容量,我们进入 if 块。

与以前一样,索引用于访问其他列表中的特定项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多