比较两个列表并输出共享连续范围的边界

时间:2017-08-16 19:21:03

标签: python

如果标题有点迟钝,我很抱歉,我无法想出更好的方法来表达它。我需要比较两个列表,listA和listB。 listB将始终与listA相同或包含一些相同的数字,listB中永远不会有一个不在listA中的数字。我需要找到listB中所有连续数字范围的极值。这些并不总是整数。所以说我有以下两个清单:

    listA = [1, 2, 3, 3.5, 4, 5, 9, 10, 11, 12, 15, 16, 17, 17.75, 18, 20, 21, 22, 25]
    listB = [1, 2, 3, 3.5, 4, 10, 15, 16, 17, 17.75, 18, 22, 25]

我想获得以下输出:

    [[1, 4], [10], [15, 18], [22, 25]]

2 个答案:

答案 0 :(得分:1)

试试这个:

listA = [1, 2, 3, 3.5, 4, 5, 9, 10, 11, 12, 15, 16, 17, 17.75, 18, 20, 21, 22, 25]
listB = [1, 2, 3, 3.5, 4, 10, 15, 16, 17, 17.75, 18, 22, 25]

output = []
currentlist = []
lowerbound = 0
for i in range(0,len(listA)):
    if listA[i] in listB:
        currentlist.append(listA[i])
    else:
        if len(currentlist) > 0:
            if currentlist[0] == currentlist[-1]:
                output.append([currentlist[0]])
            else:
                output.append([currentlist[0], currentlist[-1]])
        currentlist = []
if len(currentlist) > 0:
    if currentlist[0] == currentlist[-1]:
        output.append([currentlist[0]])
    else:
        output.append([currentlist[0], currentlist[-1]])
currentlist = [] 
print(output)

它不是很有效但它可以胜任。

答案 1 :(得分:0)

listA = [1, 2, 3, 3.5, 4, 5, 9, 10, 11, 12, 15, 16, 17, 17.75, 18, 20, 21, 22, 25]
listB = [1, 2, 3, 3.5, 4, 10, 15, 16, 17, 17.75, 18, 22, 25]

a = b = 0

ranges = []

def valid():
    return a < len(listA) and b < len(listB)


while valid():
    while valid() and listA[a] != listB[b]:
        a += 1
    current_range = [listA[a]]
    while valid() and listA[a] == listB[b]:
        a += 1
        b += 1
    if listA[a - 1] != current_range[0]:
        current_range.append(listA[a - 1])
    ranges.append(current_range)

print(ranges)  # [[1, 4], [10], [15, 18], [22, 25]]