<分区>
我在列表中有一个列表 [[1, 3, 5], [2, 4], [1,7,9]]
我的要求是遍历列表并将其缩减为
[[1,3,5,7,9], [2,4]]
。
我该怎么做?
标签 python list python-2.7
<分区>
我在列表中有一个列表 [[1, 3, 5], [2, 4], [1,7,9]]
我的要求是遍历列表并将其缩减为
[[1,3,5,7,9], [2,4]]
。
我该怎么做?
最佳答案
算法:
intersection
方法检查 item 中的任何元素是否存在于基集中。update
方法用当前项目更新基础。True
。for
循环,因为需要从第一项开始再次检查。[编辑:]
问题:
以前的代码将基本项目视为给定列表中的第一个项目,但是当此项目与其他项目没有匹配而其他项目有匹配时,代码将无法工作。
更新:
从给定列表中获取与列表中任意一项匹配的基本项。
[编辑2]:
将合并的项目插入到各自的位置
演示:
import copy
a = [[13, 15, 17], [66,77], [1, 2, 4], [1,7,9]]
#- Get base
base = None
length_a = len(a)
base_flag = True
i = -1
while base_flag and i!=length_a-1:
i += 1
item = a[i]
for j in xrange(i+1, length_a):
tmp = set(item).intersection(set(a[j]))
if tmp:
base = set(item)
base_flag = False
break
print "Selected base:", base
if base:
tmp_list = copy.copy(a)
target_index = i
tmp_list.pop(target_index)
flag = True
while flag:
flag = False
for i, item in enumerate(tmp_list):
tmp = base.intersection(set(item))
if tmp:
base.update(set(item))
tmp_list.pop(i)
flag = True
break
print "base:", base
print "tmp_list:", tmp_list
result = tmp_list
result.insert(target_index, list(base))
else:
result = a
print "\nFinal result:", result
输出:
$ 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]]
关于python - 嵌套列表,检查一个列表是否与其他列表有共同元素,如果有则加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28850487/