[英]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.