循环列表中的元组?

时间:2014-10-02 08:24:26

标签: python

我是python的新手,我正在编写一段代码如下:

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

我想要做的是循环遍历列表并取其年龄的平均值,这是每个元组的第二个元素。我在思考:

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

但这似乎是不正确的。有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

您需要在循环之前初始化age_list

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

输出:

[19, 20, 19]

修改1:

更短的解决方案是:

print [t[1] for t in list_of_tuples]

编辑2:

然后你可以得到如下平均值:

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

(或者使用你的for循环:在循环之前将平均值初始化为0并在每次迭代中添加float(age) / len(list_of_tuples)。)

答案 1 :(得分:1)

首先修复结尾双引号(“Dan”,20,“blue)

忘记循环。他们很慢。你可以用pandas数据帧做点什么。

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()

答案 2 :(得分:1)

由于您的元组列表具有3个索引,因此使用i,j,k in list_of_tuples之类的迭代,您可以通过循环访问其元素,并使用sum函数可以获得年龄总和,然后将总和除以{{ 1}}用于计算平均值!你也可以使用索引len(list_of_tuples)来访问年龄!

1

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