我是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
最佳答案
当您尝试理解一段代码时,一个好的做法是删除不相关的部分,这样您就可以看到您关心的代码正在做什么。这通常称为 MCVE .
通过您的代码片段,我们可以清理一些内容,以使我们感兴趣的行为更加清晰。
- 我们可以删除循环的内容,然后简单地打印值
- 我们可以删除第二个元组和其他我们不再使用的变量
留给我们:
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
您现在可以清楚地看到它正在做什么 - 按顺序循环列表中的每个元组,并将元组中的第一个和第二个值提取到index
和ratio
变量。
尝试一下这个 - 如果您创建大小为 1 或 3 的元组之一,会发生什么?如果您在循环中只指定一个变量而不是两个怎么办?您可以指定两个以上的变量吗?
关于python - for 循环如何在元组中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43882597/