python - 获取未存储在另一个列表中的嵌套列表

标签 python list

我有一个如下所示的输入列表

input_list = ["a", "b2","d"]

另一个列表看起来像这样

ref_list = [['a'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3', 'c4'], ['d']]

我想要做的是从 input_list 中获取 ref_list 中不存在的值列表 因此,基于这些值的结果应该是

[['c1', 'c2', 'c3', 'c4']]

起初,我的案例只有类似的内容

input_list = ["a","b","d"]
ref_list = ["a","b","c","d"]

我可以使用

missing_value = list(set(ref_list) - set(input_list))

这将提取这样的结果

["c"]

但对于 ref_list 的情况,每个索引都是一个包含单个或多个值的列表。有没有简单的方法来实现缺失值?

最佳答案

看起来像是 set.isdisjoint 的工作:

input_list = ["a", "b2","d"]
ref_list = [['a'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3', 'c4'], ['d']]

res = list(filter(set(input_list).isdisjoint, ref_list))

print(res)

输出(Try it online!):

[['c1', 'c2', 'c3', 'c4']]

用你的小数据进行基准测试:

 2.6 μs   2.6 μs   2.7 μs  python_user
 2.2 μs   2.2 μs   2.2 μs  Uttam_Velani
 0.9 μs   0.9 μs   0.9 μs  dont_talk_just_code

基准长 1000 倍 ref_list:

2150 μs  2184 μs  2187 μs  python_user
1964 μs  1981 μs  1990 μs  Uttam_Velani
 292 μs   304 μs   306 μs  dont_talk_just_code

基准代码 (Try it online!):

from timeit import repeat

def python_user(input_list, ref_list):
    return [i for i in ref_list if all(j not in i for j in input_list)]

def Uttam_Velani(input_list, ref_list):
    required_list = []
    for data in ref_list:
        if len(set(data) & set(input_list)) == 0:
            required_list.append(data)
    return required_list

def dont_talk_just_code(input_list, ref_list):
    return list(filter(set(input_list).isdisjoint, ref_list))

funcs = python_user, Uttam_Velani, dont_talk_just_code


def test(input_list, ref_list, number, format_time):
    expect = funcs[0](input_list, ref_list)
    for func in funcs:
        result = func(input_list, ref_list)
        print(result == expect, func.__name__)
    print()

    for _ in range(3):
        for func in funcs:
            times = sorted(repeat(lambda: func(input_list, ref_list), number=number))[:3]
            print(*(format_time(t / number) for t in times), func.__name__)
        print()

test(["a", "b2","d"],
     [['a'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3', 'c4'], ['d']],
     10000,
     lambda time: '%4.1f μs ' % (time * 1e6))
test(["a", "b2","d"],
     [['a'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3', 'c4'], ['d']] * 1000,
     20,
     lambda time: '%4d μs ' % (time * 1e6))

关于python - 获取未存储在另一个列表中的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69325545/

相关文章:

Python 用逗号连接字符串列表,但有一些条件 - 代码重构

python - 如何查找连续重复 3 次的列表的重复项

python - 使用索引和列名称作为 x 和 y 使用 pandas 数据框创建 Hexbin 图

python - 如何在 Windows 中重定向 Python 中的 C 级流?

python - 在Python中计算modbus的CRC16

python - 我在使用 "in range"显示 Python 列表时遇到问题

java - Set 是否有任何线程安全类

python - tensorflow 中的三阶张量与二阶张量相乘

python - 如何为多个 fastq 文件运行代码?

list - Prolog中列表中连续相似元素的子列表