比较python中的两个列表,并在某些条件下检查它们是否相等

2024-10-02 00:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python和熊猫还不熟悉。这里我有下面的dataframe,它有两个列表。你知道吗

Test             Test1
[1,1,1]          [1,2,2]
[1,2,2]          [1,0,1]
[1,0,0]          [1,1,1]
[2,2,2]          [0,0,2]

在这个datframe中,我正在比较两个列表,有一些条件只能返回true。 所以

这里,如果任何一方有2个0和1个正值,而另一方有相同的正值,那么它应该返回True,否则返回False。你知道吗

所以在这种情况下

[1,0,0]          [1,1,1]    
[2,2,2]          [0,0,2]

在这里,对他们两个来说,这都会变成现实。你知道吗

现在,我试过的是这样的

def check_two_zeros_onEither_side(tup1,tup2):
    count_on_previous = tup1.count(0)
    count_on_next = tup1.count(0)
    rem1 = [x for x in tup1 if x != 0]
    rem2 = [x for x in tup2 if x != 0]
    if count_on_previous == 2:
        if all([rem1[0] == rem2[0], rem1[0] == rem2[1]]):

但是在这里我不能处理一些异常情况,比如,索引超出范围。。有人能帮我吗?谢谢。我该如何做到这一点呢?你知道吗

def check_two_zeros_onEither_side(tup1,tup2,ins):
    count_on_previous = tup1.count(0)
    count_on_next = tup2.count(0)
    print(count_on_previous,count_on_next)
    rem1 = [x for x in tup1 if x != 0]
    rem2 = [x for x in tup2 if x != 0]
    print(rem1,rem2,len(tup1),len(tup2))
    if count_on_previous == 2 and len(rem1) == 1 and len(rem2) == 3:
        if all( [rem1[0] == rem2[0], rem1[0] == rem2[1], rem1[0] == rem2[2]]):
            print("GOin insde one",ins)
            return True
    elif count_on_next == 2 and len(rem2) == 1 and len(rem1) == 3:
        if all([rem2[0] == rem1[0], rem2[0] == rem1[1], rem2[0] == rem1[2]]):
            print("GOin insde two",ins)
            return True
        else:
            return False
    else:
        return False

这就是我试过的。。这是工作,但有没有其他办法做到这一点?你知道吗


Tags: andinforlenreturnifoncount
1条回答
网友
1楼 · 发布于 2024-10-02 00:21:31

下面呢

def compare(a, b):
    # Ensure there are two zeros on either side
    if a.count(0) == 2 or b.count(0) == 2:
        # Compute the intersection and ensure it's not zero
        return len(set(a).intersection(b)) is not 0
    return False

下面是使用Pytest进行的测试。你知道吗

import pytest

class TestDataframes:

    def test_frame_a_contains_two_zeros(self):
        a = [0, 0 ,1]
        b = [1, 1, 1]

        assert compare(a, b) is True


    def test_frame_b_contains_two_zeros(self):
            a = [2, 2, 2]
            b = [0, 0, 2]

            assert compare(a, b) is True

    def test_both_frames_contains_two_zeros(self):
            a = [0, 0, 2]
            b = [0, 0, 2]

            assert compare(a, b) is True

    def test_neither_contain_two_zeros(self):
            a = [0, 1, 2]
            b = [0, 1, 2]

            assert compare(a, b) is False

    def test_positive_number_doesnt_match(self):
            a = [2, 2, 2]
            b = [0, 0, 1]

            assert compare(a, b) is False

compare函数将返回以下内容。你知道吗

[0, 0 ,1] [1, 1, 1] #=> True
[2, 2, 2] [0, 0, 2] #=> True
[0, 0, 2] [0, 0, 2] #=> True
[0, 1, 2] [0, 1, 2] #=> False
[0, 2, 2] [0, 0, 1] #=> False

相关问题 更多 >

    热门问题