python - `if i != _i and j != _j and k != _k:` 继续但报告第一次出现?
问题描述
我有这样一个条件检查逻辑:
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)
或者,如果您将其output
用于其他用途,您可以为此目的专用一个单独的变量,或者实现一个布尔标志,该标志开始False
但True
在您添加一次时会转动。
推荐阅读
- sql-server - 从 Azure Synapse Analytics Spark Pool 连接到 Azure SQL 数据库
- sql-server - PowerBI 直接查询能否与 SQL 行级安全性一起使用?
- javascript - vue 中未定义的 CryptoJS
- arrays - 是否有用于查找矩阵长度的 Sage 函数?
- django - 从 Django 到外部 FTP 的可靠文件传输
- django - 为什么我不能在诗歌 venv 中使用 Django 执行迁移?
- java - 检查字符串是否包含数组中的字符
- azure-active-directory - PowerApps 允许来宾用户使用 AAD 集成功能连接到 Azure SQL 数据库
- amazon-web-services - 未经授权使用 php sdk 创建 AppInstaceUser
- regex - 正则表达式 - 检查名称前后是否没有空格