将列表与列表进行比较 [英] Comparing list with a list of lists

查看:49
本文介绍了将列表与列表进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 string_array = ['1','2','3','4','5','6'] 和一个列表列表 multi_list = [['1','2'],['2','3'],['2','4'],['4','5'],['5','6']]

I have a list string_array = ['1', '2', '3', '4', '5', '6'] and a list of lists multi_list = [['1', '2'], ['2', '3'], ['2', '4'], ['4', '5'], ['5', '6']]

multi_list 中每个子列表的第一个元素将在 string_array 中具有关联的条目.

The first element of each sub-list in multi_list will have an associated entry in string_array.

(子列表中没有重复的元素)

(Sublists will not have duplicate elements)

如何将这些相关元素映射到字典中,如:

How do I map these associated elements into a dictionary like:

{
'1': ['2'],
'2': ['3', '4'],
'3': [],
'4': ['5'],
'5': ['6'],
'6': []
}

推荐答案

flat = ['1', '2', '3', '4', '5', '6']
nested = [['1', '2'], ['2', '3'], ['2', '4'], ['4', '5'], ['5', '6']]

result = {key: [] for key in flat}

for key in result:
    result[key] = [nest[1] for nest in nested if key == nest[0]]


#{'1': ['2'], '2': ['3', '4'], '3': [], '4': ['5'], '5': ['6'], '6': []}

使用平面列表元素作为键,可以生成字典并使用空列表作为值.如果使用列表理解稍后生成值,则空字符串或 None 也将起作用.

Using your flat list elements as keys, you can generate a dictionary and use empty lists are the values. Empty strings or None would also work if using list comprehension to generate the values later.

然后只需遍历字典中的键和嵌套列表,即可将结果附加到适当的键上.

Then just iterate over the keys in the dictionary and your nested list to append the results to the appropriate keys.

此外;

您可以将上述内容缩小为一行,以输出相同的结果.

You can reduce the above down to a single line outputting the same result.

result = {key: [nest[1] for nest in nested if key == nest[0]] for key in flat}

输出:

{'1': ['2'], '2': ['3', '4'], '3': [], '4': ['5'], '5': ['6'], '6': []}

在评估了Juanpa的注释并测试了上述代码的效率之后,很明显,遇到大型数据集时,有更好的方法来运行它.

After assessing Juanpa's comment and testing the efficiency of the above code, it is clear there is much better ways to run this when encountering large data sets.

评论以供参考:

此解决方案是O(N * M),其中N和M是平面和嵌套的大小.您可以在O(MAX(N,M))中执行此操作.基本上,循环遍历嵌套而不是结果,然后对嵌套中的a,b进行处理:result [a] .append(b)

This solution is O(N*M) where N and M are the sizes of flat and nested. You can do this in O(MAX(N, M)). Basically, loop over nested instead of result, and do for a,b in nested: result[a].append(b)

运行上述代码1000次,在平面列表中有1000个元素,在嵌套中有1000个嵌套列表.

Running the above code, 1000 times, with 1000 elements in the flat list and 1000 nested lists in nested.. the run time is;

print(t.timeit(1000))
39.37227249999978

但是,使用下面的代码运行它具有更高的运行时间.

However running it with the below code boasts a much more efficient run time.

print(j.timeit(1000))
0.17638869999973394

代码:

result = {key: [] for key in flat}
for a, b in nested:
    if a in result:
        result[a].append(b)

这篇关于将列表与列表进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆