您在缓存中的几个位置查找了错误的元素,并且在skip
列表包含连续元素时没有正确跳过.下面是一个带有内联注释的最小修复程序,该注释指示已更改的行:
skip = [1,2]
a = [[1, None, 2], [3, 4, 5], [1, None, 7], [8, 9, 10],[11, None, 12]]
b = 0
d = {}
for i in range(len(a)):
if a[i][1]==None:
while b in skip: # Loop until skipped all elements in skip
print("found b in skip")
b = b + 1
if a[i][0] in d.keys(): # Check for first, not second element
a[i][1] = d[a[i][0]] # Use first element, not second, for lookup
else:
a[i][1] = b
d[a[i][0]] = b # Indent so we only set cached value on cache miss
b = b + 1 # Indent so we only increment b on new first element
print(d)
print(a)
Try it online!
这里有一个修改更为严格的版本,它有点像python,使用名称,而不是索引(如果可能的话):
skip = {1,2} # Use set instead of list; if skip is large, list membership check will be expensive, set will stay cheap
a = [[1, None, 2], [3, 4, 5], [1, None, 7], [8, 9, 10],[11, None, 12]]
b = 0
d = {}
for sublist in a: # Loop over values instead of indexing a over and over, C-style (slow and less readable)
first, middle, _ = sublist # Unpack to useful names (reducing risk of misindexing, and making more readable code)
# Not unpacking in for loop itself because we need to reassign elements of sublist
if middle is None: # Always use is/is not to compare to None
while b in skip:
b += 1 # Use += to avoid repeating variable name
if first in d: # No need for .keys(); "in d" has same effect as "in d.keys()" and avoids creating unnecessary keys view
sublist[1] = d[first] # Indexing needed for assignment to modify original list
else:
sublist[1] = d[first] = b # Can populate cache and reassign middle value all at once
b += 1
print(d)
print(a)
Try it online!
任何一个版本都会从问题中获得预期的输出.