Reputation: 337
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.
threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]
avg_val = []
for x in threads:
result = dsk_indpt_PI[x]/threads[x]
avg_val.append(result[x])
I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.
Upvotes: 0
Views: 1641
Reputation: 54213
The better way to do this is to use zip
.
You can try this:
avg_vals = []
for thread, dsk_ind in zip(threads, dsk_indpt_PI):
avg_vals.append(dsk_ind / thread)
zip
takes two (or more) iterables and combines them into one list of tuples with length equal to the shortest iterable.
Upvotes: 2
Reputation: 12669
Use pythonic way , One line solution:
print([item[1]/item[0] for item in zip(threads,dsk_indpt_PI)])
output:
[99.0, 98.5, 98.33333333333333, 96.75, 78.2, 67.66666666666667, 58.142857142857146, 52.0, 47.111111111111114, 42.6, 38.63636363636363, 36.583333333333336]
above list comprehension is same as:
divide=[]
for item in zip(threads,dsk_indpt_PI):
divide.append(item[1]/item[0])
print(divide)
Upvotes: 0
Reputation: 188
threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]
avg_val = []
for x in range(len(threads)):
result = dsk_indpt_PI[x]/threads[x]
avg_val.append(result)
print(avg_val)
Object is not iterable, and you cannot use result[x] as it is not a list and is being reset every time anyway.
Upvotes: 0
Reputation: 54
If you are iterating over a list with a regular for
loop, you will get the values, and not the indices. If you want the indices, you could use for i in range(len(myList)):
which would give every index i
in your list. Alternatively, you could use for index, value in enumerate(myList)
if you want both the index and the value.
Upvotes: 0
Reputation: 476739
If you iterate over a list you obtain the values of the list, not the indices.
You can use range(len(..))
to obtain the indices. Furthermore the result is result
, not result[x]
to store it into the avg_val
:
avg_val = []
for x in range(len(threads)):
result = dsk_indpt_PI[x]/threads[x]
avg_val.append(result)
But a more Pythonic version will use zip
:
avg_val = []
for a,b in zip(dsk_indpt_PI, threads):
result = a/b
avg_val.append(resul)
and we can turn this in list comprehension:
avg_val = [a/b for a,b in zip(dsk_indpt_PI, threads)]
List comprehension is a way to create a list in a more elegant way by writing generator syntax between square brackets.
Upvotes: 2