給出 2 個串列:
target = [0, 1, 2, 3, 4, 5, 6, 7]
given = [1, 2, 5, 6]
缺失的數字是[[0], [3,4], [7]]。但是,兩個串列都是回圈的,這意味著串列的末尾鏈接到第一個,所以它們實際上是這樣的:
target = [0,1,2,3,4,5,6,7,0,1,2,3,4,5,......]
given = [1,2, 5,6, 1,2, 5,6,......] # I put a space to better tell where numbers missing
這樣,缺失數字的期望輸出實際上應該是[[7,0], [3,4]]因為 7 和 0 是連續的。
我如何組成完成這項作業的功能?
uj5u.com熱心網友回復:
首先,您可以使用構建缺少補丁的串列,itertools.groupby然后在必要時粘合最左側和最右側的子串列:
import itertools
def missing(target, given):
output = [list(g) for k, g in itertools.groupby(target, key=lambda x: x in given) if not k]
if output and output[0][0] == target[0] and output[-1][-1] == target[-1]:
output[-1] = output.pop(0)
return output
print(missing([0, 1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6])) # [[3, 4], [7, 0]]
print(missing([0, 1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 5, 6, 8])) # [[0], [3, 4], [7]]
更新:如果您不想匯入itertools模塊,請output = [list(g) ...]用以下內容替換該行:
output, temp = [], [] # an empty "temporary bucket"
for x in target:
if x in given:
if temp: # if temp is nonempty
output.append(temp) # put the bucket into output
temp = [] # a new empty bucket
else: # if x is "missing"
temp.append(x) # append x into the bucket
else: # this is called when for loop is over (or target is empty)
if temp: # if the last temporary bucket is nonempty
output.append(temp)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335422.html
