Python `如果我_我和j!=_j和k!=_k:`继续,但报告第一次发生的情况?
我有这样一个条件检查逻辑:Python `如果我_我和j!=_j和k!=_k:`继续,但报告第一次发生的情况?,python,Python,我有这样一个条件检查逻辑: if k not in {None, i, j}: #don't reproduce itself if i != _i and j != _j and k != _k: continue #remove the identical copies result = [num_1, num_2, num_3] output.append(result) 然而,这个解决方案将跳过所有的重复,我想要一个逻辑,如 if i !
if k not in {None, i, j}: #don't reproduce itself
if i != _i and j != _j and k != _k:
continue #remove the identical copies
result = [num_1, num_2, num_3]
output.append(result)
然而,这个解决方案将跳过所有的重复,我想要一个逻辑,如
if i != _i and j != _j and k != _k: #continue but add the first occurrence to output.
怎么能做到呢
leetcodes中的代码
class Solution:
def threeSum(self, nums, target: int=0) -> List[List[int]]:
lookup = {nums[i]:i for i in range(len(nums))} #overwrite from the high
triplets = []
triplets_set = set()
for i in range(len(nums)):
num_1 = nums[i]
sub_target = target - num_1
# logging.debug(f"level_1_lookup: {lookup}")
for j in range(i+1, len(nums)):
num_2 = nums[j] #
_j = lookup[num_2] #
_i = lookup[num_1]
_k = j + 1
num_3 = sub_target - num_2
k = lookup.get(num_3) #
if k not in {None, i, j}: #don't reproduce itself
if i != _i and j != _j and k != _k: continue #remove the identical copies
result = [num_1, num_2, num_3]
result.sort()
result = tuple(result)
triplets_set.add(result)
triplets = [list(t) for t in triplets_set]
return triplets
只需检查
output
,您已经将result
添加到它,查看它是否包含您要查找的三元组。大概是这样的:
output = []
for i,j,k in some_iterable:
if not [i, j, k] in output:
output.append(result)
或者,如果您将
输出
用于其他内容,您可以为此专门指定一个单独的变量,或者实现一个布尔标志,当您添加该内容一次时,该标志将启动False
,但变为True
。i
,j
,和k
不是要添加到输出中的内容。基本的想法应该仍然有效。我不是OP?