繁体   English   中英

比较两个不同长度的列表,找到匹配并将匹配与第一个列表中的值相加

[英]Comparing two lists not with same length, finding matches and appending the match with value from first list

请考虑具有以下值的这两个列表。

列表一(有几百个值):

['m99076', 'm10141', 'o87909', 'o90876', 'l17237']

列表二(有几千个值):

['1', 'foo', '1', 'm10141', 's300']
['2', 'bar', '1', 'u39392', 'n623']
['3', 'fubar', '1', 'o87909', 'z039']

现在我必须检查这两个数组,看看是否有一些索引匹配。 确切地说,我想确定list_one[i] == list_two[i][3] 在我发现匹配之后,我想将list_one中的值与list_two[i][3] 因此,到另一个列表的所需输出将是(因为这两个值匹配,而剩下的那个没有):

[['foo', 'm10141'], ['fubar', 'o87090']]

一直在学习编程,但现在我正在努力解决这个问题。 我知道如果我想逐行比较这些值,我会这样做:

for i in range(len(...)):
    if list_one[i] == list_two[i][3]:
        values_list.append([list_one[i], list_two[i][3]])

但这不适用于我的情况,因为这些值可能在任何地方都匹配。

谢谢你的帮助!

你可以试试下面的,

>>> l1 = ['m99076', 'm10141', 'o87909', 'o90876', 'l17237']
>>> l2 = [['1', 'foo', '1', 'm10141', 's300'],
['2', 'bar', '1', 'u39392', 'n623'],
['3', 'fubar', '1', 'o87909', 'z039']]
>>> l3 = []
>>> for i in l1:
        for j in l2:
            if i == j[3]:
                l3.append([j[1],i])


>>> l3
[['foo', 'm10141'], ['fubar', 'o87909']]

看起来你要做的就是确保list_two项目的第三个索引存在list_one 如果这就是你想要的,这是有效的方法:

list_one = ['m99076', 'm10141', 'o87909', 'o90876', 'l17237']
list_two = [['1', 'foo', '1', 'm10141', 's300'],
            ['2', 'bar', '1', 'u39392', 'n623'],
            ['3', 'fubar', '1', 'o87909', 'z039']]
set_one = set(list_one)
output = [item for item in list_two if item[3] in set_one]
# [['1', 'foo', '1', 'm10141', 's300'], ['3', 'fubar', '1', 'o87909', 'z039']]

如果您只想要上面指定的值,只需在列表推导的开头使用(item[1], item[3])而不是item

基于list_two,循环工具适用。
下面的例子可以使用list comprehension找到。

list_one = ['m99076', 'm10141', 'o87909', 'o90876', 'l17237']
list_two = [['1', 'foo', '1', 'm10141', 's300'],
            ['2', 'bar', '1', 'u39392', 'n623'],
            ['3', 'fubar', '1', 'o87909', 'z039']]

values_list = [list(y) for y in [(x[1], x[3]) for x in list_two] if y[1] in list_one]
# [['foo', 'm10141'], ['fubar', 'o87909']]
 // There are some errors but try something like this, make a two dimensional //array like so, run an if else statement to test array values == or != this should loop through and compare ALL array indexes (:
    public class ArrayComparison {

        public static void main(String[] args) {

            String list1[] = {"m99076", "m10141", "o87909", "o90876", "l17237"};
            String list2[] = {"1", "foo", "1", "m10141", "s3002", "bar", "1", "u39392", "n6233", "fubar", "1", "o87909", "z039"};


            for(int i = 0; [i] < list1; i++){
                for(int j = 0; [j] < list2; j++){

                }if (list1[i] == list2[j]);
                System.out.println("The values are equal");
            } else
                list1[i] != list2[j];
            }
    }

暂无
暂无

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

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