說我有一些迭代。在每次迭代中,都會創建一個整數串列和一個浮點數。
1st iteration: [0,2,4,3,0] , 285 are created
2nd iteration: [0,8,5,6,0] , 230 are created
...
nth iteration: [0,9,8,1,0] , 340 are created
我想迭代地將每個 list-float 對附加到一個物件,這樣我以后可以得到具有最低浮點值的串列。例如,所需的輸出可能是這樣的:
ListColumn, FloatColumn
[0,2,4,3,0], 285
[0,8,5,6,0], 230
...
[0,9,8,1,0], 340
我嘗試將這些串列和浮點數附加到字典(以浮點數作為鍵),但由于某些浮點數可以相等,因此字典內的元素數量少于預期。有任何想法嗎?
uj5u.com熱心網友回復:
您仍然可以創建字典,但如果浮點值已經在字典中,則將其附加到現有串列中。
# create dictionary
d = {}
for i in range(n):
# get your float value and list from somewhere
float_value, l = create_float_and_list()
# if the float value already exists, append the new lists to the existing lists, otherwise create new dictionary entry
if float_value in d.keys():
d[float_value].append(l)
else:
d[float_value] = [l]
float_values = list(d.keys())
min_value = min(float_values)
# output list of lists with the given float value
print(d[min_value])
uj5u.com熱心網友回復:
我想迭代地將每個 list-float 對附加到一個物件,這樣我以后可以得到具有最低浮點值的串列。
從字面上閱讀動機,“所以我以后可以得到具有最低浮點值的串列”,這表明您根本不需要資料結構。相反,您只想簡單地分配minimum = float('inf')
(或為其分配第一個值),然后繼續分配smallest_list給您遇到的與小于minimum.
但是如果你真的想為此創建一個大型資料結構,元組串列將是一個不錯的選擇。
def get_pairs():
# Presumably some `for` loop knows how to generate these for real.
yield 285, [0,2,4,3,0]
yield 230, [0,8,5,6,0]
...
yield 340, [0,9,8,1,0]
val, lst = sorted(get_pairs())[0] # The zero-th element has the minimum.
print(lst)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520846.html
上一篇:為什么JSON.stringify中的兩個結果不同?
下一篇:如何處理物件內部的函式
