如何按矩阵位置比较两个列表中的项目?Python [英] How to compare items in two lists of lists by matrix positions? Python

查看:52
本文介绍了如何按矩阵位置比较两个列表中的项目?Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较两个列表,分别为 x a .例如:

I am trying to compare two lists of lists x and a. For example:

x = [[10, 11], [14, 12]]
a = [[9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], [15, 16]]

具体来说,我想计算在 x 中有一个元素等于或大于在相同位置的 a 中的元素的列表数量..请注意,列表 x a 中的列表中可以有任意数量的项目,并且列表中可以有任意数量的列表.

Specifically, I want to count in how many lists there is an element in x that is equal to or larger than the element in a that is in the same position. Please note, there can be any number of items in the lists and there can be any number of lists in the lists of lists x and a.

Roughly put, if x and a where only lists:
    
x = | x1, x2 |
a = | a1, a2 |

Then check: x1 >= a1, x2 >= a2. If any of these is True, count +1 else count +0.

但是,在我的情况下, x a 不是简单的列表,而是列表的列表.因此,如果 x a 中的数字被其矩阵位置索引替换,我们将得到:

However, in my situation, x and a are not simple lists but lists of lists. So if the numbers in x and a are replaced by their matrix position indices, we get:

x = [[x1_1, x1_2], [x2_1, x2_2]]
a = [[a1_1, a1_2], [a2_1, a2_2], [a3_1, a3_2], [a4_1, a4_2], [a5_1, a5_2], [a6_1, a6_2], [a7_1, a7_2]]

所以现在,我想做的具体比较如下:

So now, the specific comparison I want to do is as follows:

If:
x1_1 >= a1_1
OR # This is important, it does not have to be AND. One is enough to count +1.
x1_2 >= a1_2
Then: count + 1
Else: count + 0

If:
x1_1 >= a2_1
OR
x1_2 >= a2_2
Then: count + 1
Else: count + 0

If:
x1_1 >= a3_1
OR
x1_2 >= a3_2
Then: count + 1
Else: count + 0

Etc.

Repeat the same for [x2_1, x2_2].

我从示例中期望的结果是:(2,6)

The result I am expecting from the example is: (2, 6)

在我看来,这可以通过以下简单方式完成:

It seemed to me that this could be done in a straightforward way like:

list_3 = []
for j in a:
    for i in x:
        list_3.append(j > i)
print(list_3)

或使用列表理解:

def touch(x, a):
    return [[all([asel > xsubel for xsubel in xel for asel in ael]) for ael in a].count(False) for xel in x ]
touching = touch(x, a)
print(touching)

但是以某种方式我没有得到预期的输出(2,6).有什么建议吗?

But somehow I am not getting the expected output (2, 6). Any suggestions?

推荐答案

在两个列表上使用两个for循环将起作用

using two for loops on both the lists will work

x = [[10, 11], [14, 12]]
a = [[9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], [15, 16]]

ans=[]
for i in x:
    c=0
    for j in a:
        if(i[0]>=j[0] or i[1]>=j[1]):
            c=c+1
    ans.append(c)
print(ans)
[2,6]

当您问及广义形式时,我认为这会起作用

as you asked about the generalised form I think this will work

ans=[]
for i in x:
    c=0
    for j in a:
        for x in range(len(j)):
            if(i[x]>=j[x]):
                c=c+1
                break
    ans.append(c)
print(ans)

这篇关于如何按矩阵位置比较两个列表中的项目?Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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