好吧,虽然我可能错了,但我觉得我可以在没有函数帮助的情况下解决这个问题。 有了这种输入列表:
input=[[1,2,3],[4,5],[7],[5,4,6],[5,4]]
我想要一个结果列表,其中共享一个公共元素的内部列表被连接起来:
result=[[1,2,3],[4,5,6],[7]]
我已经找到了
if any(x in result[j] for x in input[i])
语法似乎对我的问题有帮助,但现在我被卡住了。
[编辑] 我的一个试验:
input=[[1,2,3],[4,5],[7],[5,4,6],[5,4]]
result=[input[0]]
for i in range(len(input)):
for j in range(len(result)):
if result[j] != input[i]:
if any(x in result[j] for x in input[i]):
result[j].extend(input[i])
result[j]=list(set(result[j]))
print "concatenate ",result[j], input[i]
break
else :
result.append(input[i])
print "append ", result[j], input[i]
break
>>> (bad) result
[[1, 2, 3], [4, 5], [7], [5, 4, 6], [5, 4]]
如果我使用result = [input [-1]]初始化结果,那么它可以工作:
input=[[1,2,3],[4,5],[7],[5,4,6],[5,4]]
result=[input[-1]]
for i in range(len(input)):
for j in range(len(result)):
if result[j] != input[i]:
if any(x in result[j] for x in input[i]):
result[j].extend(input[i])
result[j]=list(set(result[j]))
print "concatenate ",result[j], input[i]
break
else :
result.append(input[i])
print "append ", result[j], input[i]
break
>>> (good) result
[[4, 5, 6], [1, 2, 3], [7]]
答案 0 :(得分:1)
这是解决问题的一种更简单,性能更好的方法:
def concat(myinput) :
myinput_copy = [set(elem) for elem in myinput]
result = []
i = 0
# use `while` to avoid `for` problems (you're deleting list elems)
while i < len(myinput_copy) :
result.append(myinput_copy[i])
j = i + 1
while j < len(myinput_copy) :
if result[i] & myinput_copy[j] :
result[i] |= myinput_copy[j]
del myinput_copy[j]
j = i + 1
else :
j += 1
i += 1
return result
print concat([[1,2,3],[4,5],[7],[5,4,6],[5,4]])
它比另一个问题的J.F. Sebastian's answer快两倍,即使另一个问题需要不同的排序。
我使用了myinput,因为input
是一个内置函数,最好不要伪装它。
关于集合及其运算符:http://docs.python.org/3/tutorial/datastructures.html#sets(Python 3)
顺便说一下,你的解决方案是错的,user1189129。尝试使用此输入的代码来查看问题:input = [[1, 2, 3], [1, 8], [1, 9], [4, 5], [7], [5, 4, 6], [5, 4]]
答案 1 :(得分:0)
您可以将列表转换为普通列表(将所有变量从子列表中提取到更大的列表中),然后将它们拆分为块:
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
def plain(lst):
return set([x for y in lst for x in y])
lst = [[1,2,3],[4,5],[7],[5,4,6],[5,4]]
print list(chunks(tuple(plain(l)), 3))