你混淆了两个完全不相关语法片段。
一个是一个陈述,参见for陈述 https://docs.python.org/3/reference/compound_stmts.html#the-for-statement文档。这in
是固定语法的一部分:
for_stmt ::= “for” target_list “in” expression_list “:” suite
[“else” “:” suite]
当你使用的那一刻for
开始一行,in
部分是必需的,就像:
是必须的。不要混淆 Python 的for
带有 Cfor
环形; Python 是一个For Each构造 https://en.wikipedia.org/wiki/Foreach。因此,它不会“生成”可迭代对象,它需要可迭代对象作为输入。
另一个是一个会员试运营 https://docs.python.org/3/reference/expressions.html#membership-test-operations,并且运算符是一种类型表达:
经营者in
and not in
测试会员资格。
它适用于容器(而不仅仅是可迭代对象)。
两者都严重依赖于 Python 的 OO 本质,这是 C 无法做到的。如果您想找到其他语言中的等效项,请查看 C++、Java 或 C# 中的概念,而不是 C。
for <expr> in <iterable>
需要一个可迭代对象 https://docs.python.org/3/glossary.html#term-iterable,可以产生一个又一个元素的东西。 C++ 有一个等价概念 http://www.cplusplus.com/reference/iterator/,在 Java 中也有相似之处迭代器 https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html and streams https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html.
<expr> [not] in <expr>
仅要求右侧表达式结果支持成员资格测试,但如果没有显式钩子可用于成员资格测试,Python 将回退到迭代。这not
in not in
只是将结果反转in
手术。
C++ 和 Java 对此没有标准抽象,不同的容器类型各自实现自己的拼写(在 C++ 中大多数称之为find
, e.g. set::find http://www.cplusplus.com/reference/set/set/find/ or map::find http://en.cppreference.com/w/cpp/container/map/find,而Java通常选择contains
变化,给你Set.contains() https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#contains%28java.lang.Object%29, and Map.containsKey() https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#containsKey-java.lang.Object-).