Home > Mobile >  Using a for loop to calculate the mean of a list of tuples in Python with map and zip
Using a for loop to calculate the mean of a list of tuples in Python with map and zip

Time:03-23

I was reading the answers about question in thread: https://stackoverflow.com/questions/68538651/using-a-for-loop-to-calculate-the-mean-of-a-list-of-tuples-in-python

Although the answers have helped me, I need to question how to finish what I was unsuccessfully trying.

My code is:

`vacc_counties = [ ("Pulaski", 42.7), ("Benton", 41.4), ("Fulton", 22.1), ("Miller", 9.6), ("Mississippi", 29.4), ("Scott County", 28.1), ]

data = map(list, zip(*vacc_counties))

for i in data:

print(i)`

I have obtained these 2 lists:

['Pulaski', 'Benton', 'Fulton', 'Miller', 'Mississippi', 'Scott County']

[42.7, 41.4, 22.1, 9.6, 29.4, 28.1]

But now my problem is that I don't know how to store them in 2 variables, in order to calculate the mean after that.

I have tried something like this, among lot of other things:

i0=[]

i1=[]

for i in data:

if i==0:

i0.append(i)

else:

i1.append(i)

print(i0)

print(i1)

But the result is strange -the first blank list, plus a list into other list[[..]], and for the second element of the tuples a list with the 2 lists inside, so I think I don't know what I'm doing:

[]

[['Pulaski', 'Benton', 'Fulton', 'Miller', 'Mississippi', 'Scott County']]

[]

[['Pulaski', 'Benton', 'Fulton', 'Miller', 'Mississippi', 'Scott County'], [42.7, 41.4, 22.1, 9.6, 29.4, 28.1]]

If somebody could finish this code to obtain the mean, and explain me why I have obtained this strange result, I would appreciate it because I'm really lost.

Thank you in advance.

CodePudding user response:

You can assign the results from map function direct to variables and use it for further calculations.

Try the below solution:

vacc_counties = [ ("Pulaski", 42.7), ("Benton", 41.4), ("Fulton", 22.1), ("Miller", 9.6), ("Mississippi", 29.4), ("Scott County", 28.1), ]

data = list(map(list, zip(*vacc_counties)))
cntryNames,cntryValues = data

print(cntryNames)
print(cntryValues)

Now after this you can apply your calculations on this list.

  • Related