简体   繁体   English

比较两个不等长和不匹配元素的列表

[英]Compare two lists of unequal length and non-matching elements

I have two lists of unequal length and non-matching values as shown below: 我有两个长度不相等且值不匹配的列表,如下所示:

list_1 = [1,7,9]
list_2 = [0.1,0.2,0.3,0.8,0.11,0.12,0.13,0.14,0.19,0.009]

For each value in list_1 I want to extract its matching value in list_2 . 对于list_1每个值,我想在list_2提取其匹配值。 The result should be like this: 结果应该是这样的:

result[1:0.1,7:0.13,9:0.19]

Currently I have this: 目前我有这个:

find_minimum = min(len(list_1),len(list_2))
for i in range(find_minimum):
    print(list_1[i],list_2[i])

And this is the result: 结果如下:

1:0.1
2:0.2
3:0.3

You should look up python dictionaries , which allow a key to value mapping. 您应该查找python 字典 ,该字典允许键到值的映射。 You should also know that python is zero indexed and so the first entry of list_1 is list_1[0] . 您还应该知道python的索引为零,因此list_1的第一项是list_1[0]

With a dictionary you can write a solution like 使用字典,您可以编写解决方案,例如

result = dict() # a new dictionary, could also just write result = {}
for i in list_1:
    result[i] = list_2[i-1]
print(result)

will print 将打印

{1: 0.1, 7: 0.13, 9: 0.19}

You'll often see people use a dict comprehension for this which would look like 您会经常看到人们为此使用dict理解

result = {i: list_2[i-1] for i in list_1}

Instead of looking up the i -th index in list_2 , you want to look up the list_1[i] -th index. 您不想查找list_2i个索引, list_2要查找list_1[i]个索引。

for i in range(find_minimum):
    print(list_1[i], list_2[list_1[i]])

If that's confusing to read, save list_1[i] in a temporary variable to make it easier to understand: 如果您感到困惑,请将list_1[i]保存在一个临时变量中,以使其更易于理解:

for i in range(find_minimum):
    index = list_1[i]
    print(index, list_2[index])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM