列表比较元素的python列表

时间:2019-04-07 19:24:00

标签: python python-3.x

我想比较列表的元素。我从文本文件中解析了数据,但是无法比较列表。

这些是我解析文本文件后获得的列表:

[['Detected', '1', '-9.5', 'S19960'],['Active', '3', '-14.3', 'S19966'],
['Detected', '10788', '-10.5', 'S19961']]

[['Active', '2', '-16.3', 'S15620'],['Monitored', '2', '-18.2', 'S15629'],
 ['Detected', '2', '-8.8', 'S1003H'], ['Detected', '2', '-10.3', 'S02965'],
 ['Detected', '2', '-6.3', 'S56615'], ['Detected', '2', '-20.8', 'S10105'],
 ['Active', '2', '-20.8', 'S06940'], ['Detected', '2', '-17.8', 'S52835'],
 ['Detected', '2', '-20.8', 'S5198E'], ['Detected', '2', '-21.2', 'S56749'],
 ['Serving', '2', '-12.2', 'S02035'], ['Monitored', '2', '-24.5', 'S04919']]

代码将找到Detected个元素,并检查-9.5(列表的第二个元素)是否大于-12。如果更大,它将检查ActiveServings元素。

例如-9.5 > -14.3,如果差异大于3,则输出将用于第一个列表:

S19960 > S19966 | S19961 > S19966

第二个列表:

S1003H > S15620,S06940,S02035 | S56615 > S15620,S06940,S02035

1 个答案:

答案 0 :(得分:0)

这是一个可行的实现,它首先查找相关Detected元素(值大于-12)和要比较的元素(ActiveServing元素的索引)。然后,它将使用这些索引来解析和比较列表中的值,并生成输出字符串:

def comparisonFromList(data):

    # find indexes of Detected elements with value > -12
    detected = [i for i in range(len(data)) if data[i][0] in ['Detected'] and float(data[i][2]) > -12]

    # find indexes of Active and Serving elements
    tocompare = [i for i in range(len(data)) if data[i][0] not in ['Detected','Monitored']]

    output = ""
    for i,detect in enumerate(detected):
        if i > 0:
            output += ' | '
        output += data[detect][3];
        output += ' > '
        for j,compare in enumerate(tocompare):
            if abs(float(data[detect][2]) - float(data[compare][2])) > 3:
                if 0 < j:
                    output += ','
                output += data[compare][3];

    return output

输出(基于您提供的两个输入列表):

> print(comparisonFromList(list1))
S19960 > S19966 | S19961 > S19966

> print(comparisonFromList(list2))
S1003H > S15620,S06940,S02035 | S02965 > S15620,S06940 | S56615 > S15620,S06940,S02035

演示:https://repl.it/@glhr/55562796