0

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.

1
  • Please post the expected output for the given input example. Commented Nov 25, 2014 at 4:35

3 Answers 3

5

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)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! Makes a lot of sense and the cleaned up function is easier to read.
2

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)

1 Comment

Thank you! Clear explanation.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.