2017-10-12 19 views
0

我會很感激的幫助與以下:如何刪除包含字符串和數字的每個子列表中的字符串,並將其餘數字加入到一個列表中?

我有一個叫Fun1功能,將採取這樣的列表,

['Jo, 60, 92, 80', 'Bill, 60, 70', 'Cal, 98.5, 100, 95.5, 98'] 

,並把它變成

[['Jo', 77.3], ['Bill', 65.0], ['Cal', 98.0]] 

它以平均屬於每個人的三個數字中,然後將每個人的平均分成一個子列表。

現在我想創建一個名爲Fun2新的函數,它從 Fun1輸出,並把它變成一個列表,只有從Fun1輸出int秒。

例如,如果FUN1輸出

[['Jo', 77.3], ['Bill', 65.0], ['Cal', 98.0]] 

我想Fun2

[77.3, 65.0, 98.0] 

有誰知道的一種方法,我可以做到這一點?我知道我必須以某種方式從Fun1輸出中的每個子列表中刪除名稱,然後將這些數字連接在一個列表中,或將所有子列表放在一起,然後刪除所有名稱字符串。

我知道也許一些循環和使用del list [index]可能可以使用,但我失去了我如何使用它們。我嘗試了一些事情並沒有解決。

+1

這將是最好的讓我們看到你已經嘗試了什麼。並向我們​​展示您的代碼產生的任何錯誤。有時創建新列表比從原始列表中刪除元素更容易。 – abccd

回答

0

嘗試類似:

def fun2(): 
    fun2out = [] 
    fun1out = fun1('initial list input here') 
    for item in fun1out: 
     fun2out.append(item[1]) 
    return fun2out 

打開了該功能FUN2獲取列表並將其存儲返回的列表作爲fun1out(FUN1輸出)。 for循環訪問每個列表並將該數字附加到fun2輸出。

0

讓我們開始導入numpy的爲NP

import numpy as np 
def fun1(p:list): 
    fun1_list=[] 
    for i in p: 
     c=[] 
     temp = i.split(",") 
     c.append(temp[0]) 
     results = list(map(float,temp[1:])) 
     c.append("{:0.1f}".format(np.mean(results))) 
     fun1_list.append(c) 
    #print(fun1_list)#remove #to print the result 
    return fun1_list 
def fun2(f:fun1): 
    fun2_list=[] 
    for i in f: 
     fun2_list.append(i[1]) 
    #print(fun2_list) #remove #to print the result 
    return fun2_list 

fun_result= fun1(['Jo, 60, 92, 80', 'Bill, 60, 70', 'Cal, 98.5, 100, 95.5, 98']) 

fun2(fun_result) 

答: FUNC1列表[['Jo', '77.3'], ['Bill', '65.0'], ['Cal', '98.0']]

FUNC2列表['77.3', '65.0', '98.0']

相關問題