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

时间:2015-02-16 02:36:35

标签: python 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]])

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

感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

您可以尝试下面的内容,

>>> 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']]

答案 1 :(得分:1)

似乎您要做的就是确保list_twolist_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

答案 2 :(得分:0)

基于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']]

答案 3 :(得分:0)

 // 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];
            }
    }