Reputation: 2883
I have a function I am using to convert some numbers into a different form that requires iterating over a couple of arrays. I used two nested for loops but the results are not what I expected. I want the function to return a total of 5 variables but it returns number of variables in each array multiplied by each other. So in the following case it returns an array of 25 variables.
co_60_activities = [2 , 2 , 3 , 3 , 3]
co_60_masses = [2 , 2 , 3 , 3 , 3]
def activity(activities, masses, array):
for x in range(len(activities)):
for y in range(len(masses)):
array.append(activities[x] * masses[y] * 37000.0)
a_counts = []
activity(co_60_activities, co_60_masses, a_counts)
I found in similar posts that the conventional way to iterate through multiple lists is to use the zip function. So I changed my function to the following:
def activity(activities, masses, array):
for x , y in zip(activities , masses):
array.append(activities[x] * masses[y] * 37000.0)
This yields a "TypeError: list indices must be integers, not float" I assume I need to convert the data type somehow but I am not sure how.
Upvotes: 0
Views: 4988
Reputation: 2482
The thing with iterating over lists with for loops is that you doesn't get the index but the actual item at that iterationposition.
As an example you have the following code
examplelist = ['a','b','c']
for x in examplelist:
print x
the output would be
a
b
c
zip()
only concatenates 2 list so that you would get the following
examplelist1 = ['1','2','3']
examplelist2 = ['a','b','c']
for x,y in zip(examplelist1,examplelist2):
print x, y
output:
1 a
2 b
3 c
Upvotes: 1
Reputation: 4130
You are nearly there! The reason why you are getting the Type Error is because you are trying to access the list by its value. zip
will return the value of the element in your list.
therefore your code should have been
def activity(activities, masses, array):
for x , y in zip(activities , masses):
array.append(x * y * 37000.0)
Upvotes: 2
Reputation: 239683
zip
will give the actual items themselves, not their index. So, you can directly do
array.append(x * y * 37000.0)
Actually you don't need a function here, instead you can create a new list with list comprehension like this
a_counts = [x * y * 37000.0 for x, y in zip(co_60_activities, co_60_masses)]
Upvotes: 5