简体   繁体   中英

How does a for loop work in tuples

I am new to python, having a hard time understanding the following code. It would be great if someone can give an explanation. I have two tuples. Specifically I cant understand how the for loop works here. And what does weight_cost[index][0] mean.

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

A good practice to get into when you're trying to understand a piece of code is removing the irrelevant parts so you can see just what the code you care about is doing. This is often referred to as an MCVE .

With your code snippet there's several things we can clean up, to make the behavior we're interested in clearer.

  1. We can remove the loop's contents, and simply print the values
  2. We can remove the second tuple and the other variables, which we are no longer using

Leaving us with:

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))

Now we can drop this into the REPL and experiment:

>>> 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

You can see clearly now exactly what it's doing - looping over every tuple of the list in order, and extracting the first and second values from the tuple into the index and ratio variables.

Try experimenting with this - what happens if you make one of the tuples of size 1, or 3? What if you only specify one variable in the loop, rather than two? Can you specify more than two variables?

The for loop iterates through each tuple in the array, assigned its zero index to index and its one index to ratio.

It then checks the corresponding index in weight_cost, which is a tuple, and checks the zero index of that tuple. This is added to weight, and it that is less than or equal to capacity, we move into the if block.

Similarly, index is used to access specific items in other lists, as before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM