gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:31:40 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com