简体   繁体   中英

Looping over tuples within a list?

I am relatively new to python and I am working on a piece of code as follows:

list_of_tuples = [("Rachel",19,"red"),("Dan",20,"blue),("Hayley",19,"purple")]

What I want to do, is loop over the list and take an average of their ages, which is the second element of each tuple. I was thinking along the lines of:

for i in list_of_tuples:
    data = list(i)
    age_list = []
    age = data[1]
    age_list.append(age)

But this seems to be incorrect. Any help?

You need to initialize the age_list before the loop.

list_of_tuples = [("Rachel",19,"red"),("Dan",20,"blue"),("Hayley",19,"purple")]

age_list = []
for i in list_of_tuples:
    data = list(i)
    age = data[1]
    age_list.append(age)

print age_list

Output:

[19, 20, 19]

Edit 1:

A much shorter solution would be:

print [t[1] for t in list_of_tuples]

Edit 2:

Then you can get the average as follows:

print sum(float(t[1]) for t in list_of_tuples) / len(list_of_tuples)

(Or with your for-loop: Initialize the average to be 0 before the loop and add float(age) / len(list_of_tuples) in each iteration.)

First fix the ending double quotes on ("Dan",20,"blue)

Forget the loops. They are slow. You can do something with pandas dataframes.

list_of_tuples = [("Rachel",19,"red"),("Dan",20,"blue"),("Hayley",19,"purple")]
from pandas import DataFrame as DF
df = DF(list_of_tuples) #turns the data into a DataFrame
df[1].mean()

As your tuples list have 3 index so with an iteration like i,j,k in list_of_tuples you can access to its elements over a loop and with sum function you can earn the sum of ages then divide sum to len(list_of_tuples) for calculate the average ! also you can use the index 1 for access to ages!

>>> sum([j for i,j,k in list_of_tuples])/len(list_of_tuples)
19

or

>>> sum([i[1] for i in list_of_tuples])/len(list_of_tuples)
19

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