使用子列表创建数字不重复的新列表 [英] Using sublists to create new lists where numbers don't repeat
问题描述
提供列表:
g = [[0, 7],
[1, 2, 10, 19],
[3, 4, 5, 6, 15, 21, 24, 27],
[0, 7, 8, 9, 12, 17],
[1, 10, 11, 20],
[8, 12, 13, 18],
[14, 25],
[3, 15, 16, 22],
[9, 13, 17, 18]]
我想检查子列表中的数字,以便对于多个子列表中存在的任何数字,两个子列表可以合并形成一个新列表,例如[8, 12, 13, 18]
和[9, 13 ,17, 18]
可以结合起来得到[8, 9, 12, 13, 17, 18]
.注意:该数字不会重复,我想列出尽可能多的数字.
I want to check the numbers in the sublist so that for any number that exists in more than one sublist, both sublists can combine to form a new list, e.g. [8, 12, 13, 18]
and [9, 13 ,17, 18]
can combine to give [8, 9, 12, 13, 17, 18]
. Note: the number doesn't repeat and I want to make the biggest possible list.
我已经编写了以下代码,但是它并不完美,并且没有消除重复,有人可以帮忙吗?
I have written the following code, but it is not perfect and repeat has not be eliminated, can anyone help?
for i in g:
for j in g:
for k in i:
for l in j:
if k == l:
m=list(set(i + j))
if m not in n:
n.append(m)
我的预期输出是:
[[0, 7, 8, 9, 12, 13, 17, 18],
[1, 2, 10, 11, 19, 20],
[3, 4, 5, 6, 15, 16, 21, 22, 24, 27],
[25, 14]]
推荐答案
从列表的初始列表开始:
Starting from your initial list of lists:
>>> g = [[0, 7],
[1, 2, 10, 19],
[3, 4, 5, 6, 15, 21, 24, 27],
[0, 7, 8, 9, 12, 17],
[1, 10, 11, 20],
[8, 12, 13, 18],
[14, 25],
[3, 15, 16, 22],
[9, 13, 17, 18]]
在研究过程中,我认为您想要的是将列表其余部分中的所有匹配子列表合并到当前子列表中,然后将它们从原始列表中删除:
As you work through, I think what you want is to combine all matching sublists in the rest of the list into the current sublist, then remove them from the original list:
>>> for start_index, start in enumerate(g):
while True:
for end_index, end in enumerate(g[start_index+1:],
start_index+1):
if any(x == y for x in start for y in end):
g[start_index].extend(end)
del g[end_index]
break
else:
break
>>> g
[[0, 7, 0, 7, 8, 9, 12, 17, 8, 12, 13, 18, 9, 13, 17, 18],
[1, 2, 10, 19, 1, 10, 11, 20],
[3, 4, 5, 6, 15, 21, 24, 27, 3, 15, 16, 22],
[14, 25]]
然后您要做的就是消除重复:
Then all you have to do is get rid of duplicates:
>>> [sorted(set(l)) for l in g]
[[0, 7, 8, 9, 12, 13, 17, 18],
[1, 2, 10, 11, 19, 20],
[3, 4, 5, 6, 15, 16, 21, 22, 24, 27],
[14, 25]]
效率相对较低,但是为您提供了增强的起点(例如,如果已经设置了start
和end
,则start & end
可以替换any
).
This is relatively inefficient, but provides you a starting point for enhancement (for example, if start
and end
were already sets, start & end
could replace the any
).
这篇关于使用子列表创建数字不重复的新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!