python - 嵌套列表,检查一个列表是否与其他列表有共同元素,如果有则加入

标签 python list python-2.7

<分区>

我在列表中有一个列表 [[1, 3, 5], [2, 4], [1,7,9]]

我的要求是遍历列表并将其缩减为

[[1,3,5,7,9], [2,4]]

我该怎么做?

最佳答案

算法:

  1. 从新方法中获取基本元素。
  2. 从输入列表中删除第一项并为其创建新变量。
  3. 迭代新列表中的每一项。
  4. 通过 set intersection 方法检查 item 中的任何元素是否存在于基集中。
  5. 如果存在则执行 6,7,8,9
  6. 通过设置 update 方法用当前项目更新基础。
  7. 从列表中删除当前项目。
  8. 将标志设置为 True
  9. 打破 for 循环,因为需要从第一项开始再次检查。
  10. 创建最终结果列表添加添加基数和剩余列表。

[编辑:]

问题:

以前的代码将基本项目视为给定列表中的第一个项目,但是当此项目与其他项目没有匹配而其他项目有匹配时,代码将无法工作。

更新:

从给定列表中获取与列表中任意一项匹配的基本项。

[编辑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/

相关文章:

python - 使用 Peewee 追溯创建索引?

元组列表上的python映射

python - 为 python 2 和 3 安装了 Anaconda。无法运行 2

python - 制作python脚本等待模块函数返回

php - 非常大的 xml 文件到 mysql

python - 如何加载维基百科文章的旧(修订)内容

python - Django REST 框架 : SlugRelatedField for indirectly-related attribute?

python - 如何使用 Flask 测试客户端模拟 AJAX 请求?

python - 在字典中插入值时出现问题

python - 替换 Python 列表中的选定元素