[英]Compare elements of two lists and calculate median value
我有一個關鍵字列表:
list1 = ['key(1)', 'key(2)' ........, 'key(x)']
另一個二維列表:
list2 = [['key1','str(11)','value(11)'],['key1','str(12)','value(12)'].....,['key(1)','str(1n)','value(1n)'],['key2','str(21)','value(21)'],...,['key(2)','str(2n)','value(2n)'],........., ['key(n)','str(n1)','value(n1)'],...,['key(n)','str(nn)','value(nn)']]
我想要做的是計算列表 1 中每個關鍵字的值的中值,列表 1 中包含在列表 2 的元素中,output 將是這樣的:
output_list=[['key(1)',median(value(11),...value(1n)], ['key(2)',median(value(21),...value(2n)],.....,['key(x)',median(value(x1),...value(xn)]]
我從一個 if 語句開始:
import statistics
for i in range(0,len(list1)):
for j in range (0,len(list2)):
if list1[i] in list2[j]:
print(list1[i],statistics.median(int(list2[j][2])))
我正在嘗試打印結果,但我得到的是“int”object is not iterable
median
應該接收一個包含所有鍵值的迭代器,而你只給它一個值。
list1 = ["key(1)", "key(2)"]
list2 = [
["key(1)", "str(11)", "11"],
["key(1)", "str(12)", "12"],
["key(1)", "str(1n)", "19"],
["key(2)", "str(21)", "21"],
["key(2)", "str(2n)", "23"],
["key(2)", "str(21)", "21"],
["key(2)", "str(2n)", "253"],
]
import statistics
def values_for_key(searched_list, searched_key):
for key, string, value in searched_list:
if key == searched_key:
yield int(value)
# other solution:
# def values_for_key(searched_list, searched_key):
# return (int(value) for key, string, value in searched_list if key == searched_key)
for key in list1:
print(key, statistics.median(values_for_key(list2, key)))
就像評論中所說的那樣,如果您的列表很大,這不是一種有效的算法,您應該考慮另一種存儲它們的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.