簡體   English   中英

比較浮點數並將列表划分為 Python 中的子列表

[英]Comparing floating point numbers and dividing a list to sublists in Python

我需要幫助。 我想將帶有浮點數的列表分塊為子列表,以比較兩個十進制數字,以查看連續數字之間的差異是否在 10 范圍內。更具體地說,我的期望是將它們拆分,例如,這些數字從 70-80在一個列表中,從 80-90 在另一個列表中,依此類推。 首先,我對列表進行了排序,然后嘗試比較兩個元素,但結果與我想要的不同。 這是我比較數字的嘗試:

mylist = [125.90720268, 122.08697428, 86.70855817, 82.68482956, 75.99304643, 71.92440719, 80.92440719] 

chunked_list = []

sort_list = sorted(mylist, key = lambda x:float(x))
curr = [sort_list[0]]
print("sort_list = ", sort_list)

for x in sort_list[1:]:
    if abs(x - curr[-1]) < 10:
        chunked_list.append(curr)
        curr = [x]
    else:
        curr.append(x)
chunked_list.append(curr) ```

The result is:
[[71.92440719],
 [75.99304643],
 [80.92440719],
 [82.68482956],
 [86.70855817, 122.08697428],
 [125.90720268]]

while I want to have this result:
[[71.92440719, 75.99304643], [80.92440719, 82.68482956, 86.70855817], [122.08697428, 125.90720268]]

Also, I tried to use math.isclose() function to compare two decimal numbers, but I failed again. I really appreciate that someone tells me where I make a mistake.

You can use itertools.pairwise (or its equivalent recipe if you're using Python of version < 3.10) to iterate through the list in adjacent pairs, and append to the output list a new sub-list if the difference between the pair is greater超過 10,同時繼續將當前項目附加到最后一個子列表:

from itertools import pairwise

output = []
for a, b in pairwise(sorted(mylist)):
    if not output or b - a > 10:
        output.append([] if output else [a])
    output[-1].append(b)

給定您的示例輸入, output變為:

[[71.92440719, 75.99304643, 80.92440719, 82.68482956, 86.70855817], [122.08697428, 125.90720268]]

演示: https://replit.com/@blhsing/ImperturbableCrushingAdministrator

編輯:由於您更新了您的問題,修改后的要求是數字應以 10 的倍數分組,因此當當前項目除以 10 與最后一個項目的第一項不同時,您可以 append 列表的新子列表 output 列表子列表除以 10:

output = []
for i in sorted(mylist):
    if not output or i // 10 != output[-1][0] // 10:
        output.append([])
    output[-1].append(i)

output變為:

[[71.92440719, 75.99304643], [80.92440719, 82.68482956, 86.70855817], [122.08697428, 125.90720268]]

演示: https://replit.com/@blhsing/ElaborateUsedRotation

暫無
暫無

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

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