簡體   English   中英

遍歷列表中的元組?

[英]Looping over tuples within a list?

我是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)

但這似乎是不正確的。 有什么幫助嗎?

您需要在循環之前初始化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) 。)

首先將結尾的雙引號固定在(“ 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()

由於您的元組列表具有3個索引,因此使用i,j,k in list_of_tuples類的迭代i,j,k in list_of_tuples您可以循環訪問其元素,並且可以使用sum函數獲得年齡的總和,然后將sum除以len(list_of_tuples)來計算平均 ! 您也可以使用索引1來訪問年齡!

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM