Python 嵌套列表,检查一个列表是否与另一个列表具有公共元素,如果是,则连接
我在列表中有一个列表,上面写着Python 嵌套列表,检查一个列表是否与另一个列表具有公共元素,如果是,则连接,python,list,python-2.7,Python,List,Python 2.7,我在列表中有一个列表,上面写着[[1,3,5],[2,4],[1,7,9] 我的要求是我想遍历列表并将其缩减为 [[1,3,5,7,9],[2,4]] 我该怎么做呢?效率很低,但这确实起到了关键作用: def combine_lists(lists): # Keep a set of processed items skip = set() for i, a in enumerate(lists): # If we already used this l
[[1,3,5],[2,4],[1,7,9]
我的要求是我想遍历列表并将其缩减为
[[1,3,5,7,9],[2,4]]
我该怎么做呢?效率很低,但这确实起到了关键作用:
def combine_lists(lists):
# Keep a set of processed items
skip = set()
for i, a in enumerate(lists):
# If we already used this list, skip it
if i in skip:
continue
for j, b in enumerate(lists[i + 1:], i + 1):
# Use a set to check if there are common numbers
if set(a) & set(b):
skip.add(j)
for x in b:
if x not in a:
a.append(x)
# yield all lists that were not added to different lists
for i, a in enumerate(lists):
if i not in skip:
yield a
[edit]刚刚注意到顺序不再重要(您的输出表明它确实重要),这让事情变得更简单:)
这个版本应该是相当理想的:
def combine_lists(lists):
# Keep a set of processed items
skip = set()
sets = map(set, lists)
for i, a in enumerate(sets):
# If we already returned this set, skip it
if i in skip:
continue
for j, b in enumerate(sets[i + 1:], i + 1):
# Use a set to check if there are common numbers
if a & b:
skip.add(j)
a |= b
# yield all sets that were not added to different sets
for i, a in enumerate(sets):
if i not in skip:
yield a
算法:
intersection
方法检查项目中的任何元素是否存在于基本集合中Update
方法使用当前项更新基础True
for
循环,因为需要从第一项开始再次检查$ python task4.py
Selected base: set([1, 2, 4])
base: set([1, 2, 4, 7, 9])
tmp_list: [[13, 15, 17], [66, 77]]
Final result: [[13, 15, 17], [66, 77], [1, 2, 4, 7, 9]]
减少这一比例的标准是什么?奇数和偶数?为什么要合并列表1和列表3?仅仅因为他们共享元素
1
?@tim是的,如果他们有共同的元素,我想合并它们,你可以给出不止一个例子吗@DeadjangdJoker:这个[[1,2],[3,4],[1,5,3],[5]].
的输出是什么?工作正常:)…谢谢:)请注意,这是如何得到4次投票和一个接受(@deadjangdJoker),这不起作用:。还要注意的是,大多数集合方法,如交集、更新等,对于任何iterable都可以正常工作,因此不需要转换为集合。@AshwiniChaudhary:是的,正确。我会在一段时间内更新。@AshwiniChaudhary:现在检查。更新并让我知道是否有更多改进,或者是否对其他测试用例不起作用?@deadjangdjoker:根据Ashwini的评论,现在检查一下。尝试过这个…力似乎对我起作用:(…谢谢aneways:)第一个解决方案似乎很好,但第二个不起作用:@AshwiniChaudhary:oops。。。似乎我在复制时出错了,最后一个列表应该是集合
。谢谢你的提醒:)
$ python task4.py
Selected base: set([1, 2, 4])
base: set([1, 2, 4, 7, 9])
tmp_list: [[13, 15, 17], [66, 77]]
Final result: [[13, 15, 17], [66, 77], [1, 2, 4, 7, 9]]
a = [[1,2], [3,4 ], [1,5,3], [5]] # output: [set([1, 2, 3, 4, 5])]
# a = [[1, 3, 5], [2, 4], [1,7,9]] # output: [set([1, 3, 5, 7, 9]), set([2, 4])]
# convert them to sets
a = [set(x) for x in a]
go = True
while go:
merged = False
head = a[0]
for idx, item in enumerate(a[1:]):
if head.intersection(item):
a[0] = head.union(item)
a.pop(idx + 1)
merged = True
break
if not merged:
go = False
print a