簡體   English   中英

Python - 比較兩個嵌套列表並編寫第三個嵌套列表

[英]Python - comparing two nested lists and writing a third nested list

some_list = [[app_num, product, prod_size, prod_amt]]
other_list = [[app_num, product, prod_size, prod_amt]]

我有兩個列表列表。 app_um的some_list和other_list之間沒有匹配項。 但是,對於other_list中的給定app_num,product,prod_size_和prod_amt可能與some_list中給定app_num中的相同。 我正在嘗試創建一個與some_list相同的final_some_list,除非它已從some_list刪除任何列表元素,如果該列表元素具有相同的產品,prod_size和prod_amt作為other_list中的元素。

我已經嘗試過嵌套for循環,列表理解(下面是許多失敗嘗試的一些例子)。

final_some_list = [app for app in some_list for other_app in other_list 
if not app[1] == other_app[1] and app[2] == other_app[2] and app[3] == 
other_app[3]

final_some_list = [app for app in some_list for other_app in other_list 
if not app[1] and app[2] and app[3] == in other_app
final_some_list = [x for x in some_list if all(x[1:] != y[1:] for y in other_list)]

編輯

上面的解是Onm ),其中n == len(some_list)m == len(other_list) 如果需要,可以將其設為On log m )。 other_list的所有元素的所有尾部放在二叉搜索樹中(假設這些元素是可以的),現在查詢該樹是O (log m )。 如果元素是可清除的,您甚至可以使用On )解決方案,因為查詢哈希集是O (1)。

順便說一下:這兩個列表的元素對我來說就像元組一樣,這會讓你更接近一個更好的解決方案。

只有第一個比較包含not屬性,添加!=到所有比較,這應該工作:

final_some_list = [app for app in some_list for other_app in other_list 
if app[1] != other_app[1] and app[2] != other_app[2] and app[3] != 
other_app[3]]

暫無
暫無

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

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