![](/img/trans.png)
[英]What is the Pythonic way to find the longest common prefix of a list of lists?
[英]What is a pythonic way to find set of lists which have all common elements?
假設我有一個列表a=[[1,2],[1.00000001,2.000000001],[2,3],[4,5],[4.0000000002,5.0000006]]
,我只想得到a=[[1,2],[2,3],[4,5]]
因為其他列表的所有元素都靠近列表中的某個其他元素。 我們如何在 Python 中做到這一點? 可以以某種方式使用set
嗎?
我嘗試使用 numpy 的allclose
function 但是我們必須比較列表 a 中的所有 n(n-1)/2 對,這顯然是低效的。 有沒有更有效的 Pythonic 方式來做到這一點?
編輯:我只是在示例中使用了一些整數,輸入通常是浮點數。
如果值是這樣的(即看起來像浮點不准確,您可以將值四舍五入到您感興趣的精度,然后使用set()
將事物減少為唯一元組:
>>> a=[[1,2],[1.00000001,2.000000001],[2,3],[4,5],[4.0000000002,5.0000006]]
>>> a_r = [tuple(round(v, 2) for v in pair) for pair in a]
[(1, 2), (1.0, 2.0), (2, 3), (4, 5), (4.0, 5.0)]
>>> set(a_r)
{(2, 3), (4, 5), (1, 2)}
對於列表中的數據樣本和預期結果,因為您可以使用 Numpy,我建議使用dtype
轉換為 integer 並使用numpy 。
所以,給定你的清單:
a=[[1,2],[1.00000001,2.000000001],[2,3],[4,5],[4.0000000002,5.0000006]]
您可以執行以下操作:
import numpy as np
a_np = np.unique(np.array(a, dtype=np.uint), axis=0)
print(a_np)
# [[1 2]
# [2 3]
# [4 5]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.