我一直在努力解决这个问题两天,我需要帮助。我需要在列表列表中找到重复的元素
list_of_list = [(a1, b1, c1), (a2, b2, c2), ..., (an, bn, cn)]
其中“a”和“b”元素是整数,“c”元素是浮点数。
因此,如果例如a1 == a2
或a1 == bn
,我需要创建一个包含整个列表元素的新列表,我需要为所有列表(a,b,c)迭代列表清单。换句话说,我需要所有包含多个列表中存在的元素的列表。我只需要比较“a”和“b”元素,但在最终列表中获得相关的值“c”。
例如:
list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ]
desired_result=[(1, 2, 4.99), (1, 4, 3.00), (5, 1, 1.12)]
我尝试了许多想法......但没有什么好看的:
MI_network = [] #repeated elements list
genesis = list(complete_net) #clon to work on
genesis_next = list(genesis) #clon to remove elements in iterations
genesis_next.remove(genesis_next[0])
while genesis_next != []:
for x in genesis:
if x[0] in genesis_next and x[1] not in genesis_next:
MI_network.append(x)
if x[0] not in genesis_next and x[1] in genesis_next:
MI_network.append(x)
genesis_next.remove(genesis_next[0])
答案 0 :(得分:-1)
这就是我怎么做的,因为我不知道collections.defaultdict()
。
list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ]
results = []
for i_sub, subset in enumerate(list_of_list):
# test if ai == aj
rest = list_of_list[:i_sub] + list_of_list[i_sub + 1:]
if any(subset[0] == subrest[0] for subrest in rest):
results.append(subset)
# test if ai == bj
elif any(subset[0] == subrest[1] for subrest in rest):
results.append(subset)
# test if bi == aj
elif any(subset[1] == subrest[0] for subrest in rest):
results.append(subset)
print(results) # -> [(1, 2, 4.99), (1, 4, 3.0), (5, 1, 1.12)]
答案 1 :(得分:-1)
使用您的想法,您可以尝试:
MI_network = []
complete_net = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99)]
genesis = list(complete_net)
while genesis != []:
for x in genesis:
for gen in genesis:
if x[0] in gen and x[1] not in gen:
if x[0] != gen[2] and x[1] != gen[2]:
if x not in MI_network:
MI_network.append(x)
elif x[0] not in gen and x[1] in gen:
if x[0] != gen[2] and x[1] != gen[2]:
if x not in MI_network:
MI_network.append(x)
elif x[0] not in gen and x[1] not in gen:
pass
genesis.remove(genesis[0])
print(MI_network)
[(1, 2, 4.99), (1, 4, 3.0), (5, 1, 1.12)]