![](/img/trans.png)
[英]How can I form a list of matching elements in two lists, including duplicates?
[英]How can I optimize the intersections between lists with two elements and generate a list of lists without duplicates in python?
我的循環需要幫助。 在我的腳本中,我從輸入文件中提取了兩個龐大的列表(每個~~ 87.000整數)。
用幾個數字檢查此示例:
我們有兩個列表:
nga = [1, 3, 5, 34, 12]
ngb = [3, 4, 6, 6, 5]
這兩個列表的事項,因為每個位置與在其他列表中的同一位置,因此與順序1
在nga
與相關的3
在ngb
, 3
與4
,等...
所以我想要的是這個輸出:
listoflists = [[1, 3, 4], [5, 6, 12, 34]]
到目前為止,我有這個循環:
listoflists = []
for p in range(0, len(nga)):
z = [nga[p], ngb[p]]
for a, b in zip(nga, ngb):
if a in z:
z.append(b)
else:
pass
if b in z:
z.append(a)
else:
pass
listoflists.append(z)
當我使用整個列表時,會出現問題,因為它崩潰了,並給我分段錯誤。 那么,我該怎么辦?
提前致謝。
我用這個漂亮的函數解決了我的問題:
net = []
for a, b in zip(nga, ngb):
net.append([a, b])
def nets_super_gen(net):
not_con = list(net)
netn = list(not_con[0])
not_con.remove(not_con[0])
new_net = []
while len(netn) != len(new_net):
new_net = list(netn)
for z in net:
if z[0] in netn and z[1] not in netn:
netn.append(z[1])
not_con.remove(z)
elif z[0] not in netn and z[1] in netn:
netn.append(z[0])
not_con.remove(z)
try:
if z[0] in netn and z[1] in netn:
not_con.remove(z)
except ValueError:
pass
return(netn, not_con)
list_of_lists, not_con = nets_super_gen(net)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.