Python if 语句中“in”的用法和含义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19775692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:34:53  来源:igfitidea点击:

Use and meaning of "in" in an if statement?

python

提问by Scherf

In an example from Zed Shaw's Learn Python the Hard Way, one of the exercises displays the following code:

在 Zed Shaw 的Learn Python the Hard Way 的一个示例,其中一个练习显示了以下代码:

next = raw_input("> ")
if "0" in next or "1" in next:
    how_much = int(next)

I'm having a hard time understanding the meaning of inin this statement. I'm used to using ifstatements, such as in javascript, where the syntax is something like:

我很难理解in这句话中的含义。我习惯于使用if语句,例如在 javascript 中,其语法类似于:

var = 5;
if (var > 3) {
    //code  to be executed
}

Is this if/ instatement (in python) the same as if()in javascript?

这个if/in语句(在 python 中)与if()在 javascript 中相同吗?

Finding an answer to this has been tricky because the inis such a short string to narrow down an answer via search engine, and I don't know the proper name for its operation.

找到这个问题的答案很棘手,因为这in是一个很短的字符串,无法通过搜索引擎缩小答案的范围,而且我不知道其操作的正确名称。

采纳答案by Tim Pietzcker

It depends on what nextis.

这取决于是什么next

If it's a string (as in your example), then inchecks for substrings.

如果它是一个字符串(如您的示例中所示),则in检查子字符串。

>>> "in" in "indigo"
True
>>> "in" in "violet"
False
>>> "0" in "10"
True
>>> "1" in "10"
True

If it's a different kind of iterable (list, tuple, set, dictionary...), then inchecks for membership.

如果它是不同类型的可迭代对象(列表、元组、集合、字典...),则in检查成员资格。

>>> "in" in ["in", "out"]
True
>>> "in" in ["indigo", "violet"]
False

In a dictionary, membership is seen as "being one of the keys":

在字典中,成员资格被视为“是关键之一”:

>>> "in" in {"in": "out"}
True
>>> "in" in {"out": "in"}
False

回答by utdemir

Using a in bis simply translates to b.__contains__(a), which shouldreturn if b includes a or not.

使用a in bis 简单地转换为b.__contains__(a),如果 b 包括 a 或不包括,它应该返回。

But, your example looks a little weird, it takes an input from user and assigns its integer value to how_muchvariable if the input contains "0"or "1".

但是,您的示例看起来有点奇怪,它接受来自用户的输入,如果输入包含或,则将其整数值分配给how_much变量。"0""1"

回答by jramirez

Maybe these examples will help illustrate what indoes. It basically translate to Is this item in this other item?

也许这些例子将有助于说明什么in。它基本上翻译成Is this item in this other item?

listOfNums = [ 1, 2, 3, 4, 5, 6, 45, 'j' ]

>>> 3 in listOfNums:
>>> True

>>> 'j' in listOfNums:
>>> True

>>> 66 in listOfNums:
>>> False

回答by jwarner112

You are used to using the javascript if, and I assume you know how it works.

您已经习惯使用 javascript if,我假设您知道它是如何工作的。

inis a Pythonicway of implementing iteration. It's supposed to be easier for non-programmatic thinkers to adopt, but that can sometimes make it harder for programmatic thinkers, ironically.

in是一种实现迭代的Pythonic方式。对于非程序化思想家来说,它应该更容易采用,但具有讽刺意味的是,这有时会使程序化思想家更难采用。

When you say if x in y, you are literally saying:

当您说 时if x in y,您实际上是在说:

"if xis in y", which assumes that yhas an index. In that ifstatement then, each object at each index in yis checked against the condition.

“if xis in y”,它假设y有一个索引。if然后在该语句中,y根据条件检查每个索引处的每个对象。

Similarly,

相似地,

for x in y

for x in y

iterates through x's in y, where yis that indexable set of items.

遍历x's in yy可索引的项目集在哪里。

Think of the ifsituation this way (pseudo-code):

if这种方式思考情况(伪代码):

for i in next:
    if i == "0" || i == "1":
        how_much = int(next)

It takes care of the iteration over nextfor you.

它会next为您处理迭代。

Happy coding!

快乐编码!

回答by Ananta

Here raw_inputis string, so if you wanted to check, if var>3then you should convert next to double, ie float(next)and do as you would do if float(next)>3:, but in most cases

raw_inputstring,所以如果你想检查,if var>3那么你应该转换为双倍,即float(next)按照你的方式做if float(next)>3:,但在大多数情况下

回答by jgranger

the reserved word "in" is used to look inside an object that can be iterated over.

保留字“in”用于查看可以迭代的对象内部。

list_obj = ['a', 'b', 'c']
tuple_obj = ('a', 1, 2.0)
dict_obj = {'a': 1, 'b': 2.0}
obj_to_find = 'c'
if obj_to_find in list_obj:
    print('Object {0} is in {1}'.format(obj_to_find, list_obj))
obj_to_find = 2.0
if obj_to_find in tuple_obj:
    print('Object {0} is in {1}'.format(obj_to_find, tuple_obj))
obj_to_find = 'b'
if obj_to_find in dict_obj:
    print('Object {0} is in {1}'.format(obj_to_find, dict_obj))

Output:

输出:

Object c is in ['a', 'b', 'c']
Object 2.0 is in ('a', 1, 2.0)
Object b is in {'a': 1, 'b': 2.0}

However

然而

cannot_iterate_over = 5.5
obj_to_find = 5.5
if obj_to_find in cannot_iterate_over:
    print('Object {0} is in {1}'.format(obj_to_find, cannot_iterate_over))

will throw

会扔

Traceback (most recent call last):
File "/home/jgranger/workspace/sandbox/src/csv_file_creator.py", line 43, in <module>
if obj_to_find in cannot_iterate_over:
TypeError: argument of type 'float' is not iterable

In your case, raw_input("> ") returns iterable object or it will throw TypeError

在您的情况下, raw_input("> ") 返回可迭代对象,否则会抛出 TypeError

回答by abarnert

Since you claim to be used to JavaScript:

由于您声称已习惯使用 JavaScript:

The Python inoperator is similar to the JavaScript inoperator.

Pythonin运算符类似于 JavaScriptin运算符。

Here's some JavaScript:

这是一些 JavaScript:

var d = {1: 2, 3: 4};
if (1 in d) {
    alert('true!');
}

And the equivalent Python:

和等效的 Python:

d = {1: 2, 3: 4}
if 1 in d:
    print('true!')

With objects/dicts, they're nearly identical, both checking whether 1is a key of the object/dict. The big difference, of course, is that JavaScript is sloppily-typed, so '1' in dwould be just as true.

对于对象/字典,它们几乎相同,都检查是否1是对象/字典的键。当然,最大的区别在于 JavaScript 是草率类型的,所以'1' in d同样如此。

With arrays/lists, they're very different. A JS array is an object, and its indexes are the keys, so 1 in [3, 4, 5]will be true. A Python list is completely different from a dict, and its inoperator checks the values, not the indexes, which tends to be more useful. And Python extends this behavior to all iterables.

对于数组/列表,它们非常不同。甲JS数组是一个对象,并且其索引是键,所以1 in [3, 4, 5]true。Python 列表与 dict 完全不同,它的in运算符检查,而不是索引,后者往往更有用。Python 将此行为扩展到所有可迭代对象。

With strings, they're even more different. A JS string isn't an object, so you will get a TypeError. But a Python stror unicodewill check whether the other operand is a substring. (This means 1 in '123'is illegal, because 1can't be a substring of anything, but '1' in '123'is true.)

有了字符串,它们就更加不同了。一个 JS 字符串不是一个对象,所以你会得到一个TypeError. 但是 Python strorunicode会检查另一个操作数是否是substring。(这意味着1 in '123'是非法的,因为1不能是任何东西的子串,但它'1' in '123'是真的。)

With objects as objects, in JS there is of course no distinction, but in Python, objects are instances of classes, not dicts. So, in JS, 1 in dwill be true for an object if it has a member or method named '1', but in Python, it's up to your class what it means—Python will call d.__contains__(1), then, if that fails, it tries to use your object as an utterable (by calling its __iter__, and, if that fails, by trying to index it with integers starting from 0).

以对象为对象,在JS中当然没有区别,但在Python中,对象是类的实例,而不是字典。因此,在 JS 中,1 in d如果对象具有名为 的成员或方法'1',则该对象为真,但在 Python 中,这取决于您的类的含义——Python 将调用d.__contains__(1),然后,如果调用失败,它会尝试使用您的对象作为一个 utterable(通过调用它的__iter__,如果失败,则尝试用从 开始的整数索引它0)。

Also, note that JS's in, because it's actually checking for object membership, does the usual JS method-resolution-order search, while Python's in, because it's checking for keys of a dict, members of a sequence, etc., does no such thing. So, technically, it's probably a bit closer to the hasOwnPropertymethod than the inoperator.

另外,请注意 JS 的in,因为它实际上是在检查对象成员资格,执行通常的 JS 方法解析顺序搜索,而 Python 的in,因为它正在检查 dict 的键、序列的成员等,不做这样的事情。所以,从技术上讲,它可能hasOwnPropertyin操作符更接近方法。

回答by bp14

This may be a very late answer. inoperator checks for memberships. That is, it checks if its left operand is a member of its right operand. In this case, raw_input() returns an strobject of what is supplied by the user at the standard input. So, the ifcondition checks whether the input contains substrings "0" or "1". Considering the typecasting (int()) in the following line, the ifcondition essentially checks if the input contains digits 0 or 1.

这可能是一个很晚的答案。 in操作员检查成员资格。也就是说,它检查其左操作数是否是其右操作数的成员。在这种情况下, raw_input() 返回用户在标准输入处提供的内容的str对象。因此,if条件检查输入是否包含子字符串“0”或“1”。考虑下一行中的类型转换(int()),if条件本质上检查输入是否包含数字 0 或 1。