python - 消除for循环中的 "found"变量

标签 python python-3.x anti-patterns

过去,我们在迭代列表时使用“found”变量来表示您找到了匹配项。现在有使用带有 for 循环的“else”的 pythonic 结构来消除使用“found”变量。例如,这工作得很漂亮:

l = [1, 2, 3]
magic_number = 4

for n in l:
    if n == magic_number:
        print("Magic number found")
        break
else:
    print("Magic number not found")

但是,我有一个嵌套的 for 循环,并且我需要存储第二个数组(下面的 m)中不存在但确实存在于第一个数组(下面的 l)中的所有项目。我只是不确定如何实现这个结构。我不想(如果我不需要)使用“找到的”变量...有什么想法吗?

l = [1, 2, 3]
m = [4, 5, 6]

not_found = list()

for n in l:
   for o in m:
      if n == o:
         print("Found a match")
         break
   else:
      print("No match found")

   not_found.append(o)

最佳答案

如果您想要 l 中不在 m 中的所有元素,您可以进行理解(如 @PatrickHaugh 建议)或集合操作。

理解:

>>> l = [1, 2, 3]
>>> m = [4, 5, 6]
>>> [o for o in l if o not in m]
[1, 2, 3]

如果您更喜欢使用集合操作:

>>> l = {1, 2, 3}
>>> m = {4, 5, 6}
>>> l - m
{1, 2, 3}
>>> l = {1, 2, 3, 4}
>>> l - m
{1, 2, 3}

请注意,这里的lmsets .

关于python - 消除for循环中的 "found"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50401794/

相关文章:

jquery - 如何在django中使用AJAX根据FK获取对象

python - 神经网络模型没有提高准确性。规模问题还是模型问题?

python - 如何在 python 中合并或连接两个 midi 文件

python - 根据 pandas 中的其他列内容对列进行操作

Python JIRA Rest api - 过滤变更日志

python - 从日期到字符串的 Pyspark 类型转换问题

Python urllib.request.Request参数 'data'对象类型

angularjs - 在 Controller 中使用 Angular 的 $watch 是反模式吗?

需要 Java 设计模式建议。 (具有静态参数和方法的处理程序)

.net - 创建自定义事件 - 对象发送者还是类型化发送者?