Python 比较两个列表并输出共享连续范围的边界
对不起,如果标题有点迟钝,我想不出更好的表达方式了。我需要比较两个列表,listA和listB。listB将始终与listA相同或包含一些相同的数字,listB中永远不会有不在listA中的数字。我需要找到列表B中所有连续数字范围的极值。这些并不总是整数。假设我有以下两个列表:Python 比较两个列表并输出共享连续范围的边界,python,Python,对不起,如果标题有点迟钝,我想不出更好的表达方式了。我需要比较两个列表,listA和listB。listB将始终与listA相同或包含一些相同的数字,listB中永远不会有不在listA中的数字。我需要找到列表B中所有连续数字范围的极值。这些并不总是整数。假设我有以下两个列表: 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
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]]
试试这个:
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)
虽然效率不高,但它确实起到了作用。listA=[1,2,3,3.5,4,5,9,10,11,12,15,16,17,17.75,18,20,21,22,25]
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]]
listB=[1,2,3,3.5,4,10,15,16,17,17.75,18,22,25]
a=b=0
范围=[]
def valid():
返回a
您是否尝试了一些无法与我们共享的内容?22和25不是连续的数字,但您已将它们添加到构成列表b
最后一个元素的范围列表中。为什么?@Ajax1234是的,我希望我能想出一个更好的术语。我的意思不一定是1,2,3,4中的连续,我指的是第一个列表中的连续数字。因此,如果listA有22,25,26,28,300这样的值,listB有相同的范围,那么这个特定范围的数字的输出将是[22300]。这有意义吗?