Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查Python for循环的所有迭代中是否有正确的内容_Python - Fatal编程技术网

检查Python for循环的所有迭代中是否有正确的内容

检查Python for循环的所有迭代中是否有正确的内容,python,Python,我试图找到的是一个变量,它是列表中任何列表的一个元素。如果它是其中任何一个的元素,那么我将使用continue移动到下一个块。如果它不是任何列表的成员,那么我想在列表列表中创建一个新列表,并将变量作为该列表的唯一条目 我问这个问题的原因是,如果if语句得到满足,或者其他迭代都没有得到满足,这两种情况都会看到相同的结果,一个经过这个块的延续 for group in groups: if point in group: continue else:

我试图找到的是一个变量,它是列表中任何列表的一个元素。如果它是其中任何一个的元素,那么我将使用
continue
移动到下一个块。如果它不是任何列表的成员,那么我想在列表列表中创建一个新列表,并将变量作为该列表的唯一条目

我问这个问题的原因是,如果if语句得到满足,或者其他迭代都没有得到满足,这两种情况都会看到相同的结果,一个经过这个块的延续

for group in groups:
    if point in group:
        continue
    else:

        # if point not an element of any group, 
          create group in groups with variable as only element
更新:

这样行吗?有没有更简洁的方法

for group in groups:
    if point in group:
        groupCheck = 1
    else:
        pass
if not groupCheck:
    # Create a new list including point

为什么不把if语句放在循环之外呢

found = False

for group in groups:
    if point in group:
        found = True
        break

if not found:
    groups.append([point])

颠倒逻辑,使用
for
循环的
else
子句创建新组

for group in groups:
  if point in group:
    break
else:
  create_new_group(point)
或者只需使用
any()

做一个函数

def check_matches(point, groups):
    for group in groups:
        if point in group:
            return true
    return false

if not check_matches(point, groups):
    groups.append([point])
if not any(point in group for group in groups):
    groups.append([point])
您可以让它保持简单,这取决于您试图用它做什么,或者将它构建成一个更复杂的函数:

def get_groups(point, groups):
    if not check_matches(point, groups):
        groups.append([point])
    return groups

groups = get_groups(point, groups)

这里有一些简单的列表理解功能,但鉴于您对Python的熟悉程度,我不推荐它们。这肯定会让你感到困惑,并在将来犯更多错误。

尝试使用内置的
any()
函数

def check_matches(point, groups):
    for group in groups:
        if point in group:
            return true
    return false

if not check_matches(point, groups):
    groups.append([point])
if not any(point in group for group in groups):
    groups.append([point])

问题是,当你在一个小组中识别出它之后,你在做什么?如果没有,找到后再回来。这应该是两个函数:
查找
添加
。这两个建议看起来都很好:)谢谢Ignacio