2014-11-13 46 views
-4

我想要做的是列出一個像[['Smith','13','19','8','12']「的列表)從中取出整數並將它們全部加起來計算平均值。任何人都知道如何做到這一點?解析包含Str和Ints的列表

+6

您是否嘗試過什麼自己了嗎? SO不是免費的編碼服務;你不能在這裏複製/粘貼作業。請告訴我們您到目前爲止所做的嘗試,我們將非常樂意幫助解決您遇到的任何具體問題。 – iCodez

+0

如果你是誰負責這個數據結構:改變它! – Matthias

+0

@Mike你可以接受最能幫助你的答案。 – AHuman

回答

1

你可以這樣做:

# go through each member of your list and call the 
# builtin string method `isdigit` check out the documentation 
digits = [int(s) for s in your_list if s.isdigit()] 
# use the built in `sum` function and the builtin `len` function 
sum(digits)/len(digits) 
+0

這幫了很大忙,我在一些問題上得到零分,但這讓我明白我在做什麼錯了謝謝 – Mike

0

使用try

sum = 0 
number_of_ints = 0 
for items in ['Smith', '13', '19', '8', '12']: 
    try: 
     sum += int(items) 
     number_of_ints+=1 
    except: 
     pass 
print sum/number_of_ints 

基本上,這試圖將其添加到sum。如果失敗,則繼續。

0

試試這個:

myList = ['Smith', '13', '19', '8', '12'] 
count = 0 
total = 0 

for i in myList: 
    if i.isdigit(): 
     count += 1 
     total += int(i) 

average = total/count