python 成员运算符
Python has two membership operators – “in” and “not in”. They are used to check if an element is present in a sequence or not.
Python有两个成员运算符-“ in”和“ not in”。 它们用于检查元素是否按顺序存在。
运算符中的Python (Python in Operator)
This operator returns True if the specified element is present in the sequence. The syntax of “in” operator is:
如果序列中存在指定的元素,则此运算符返回True。 “ in”运算符的语法为:
x in y
Here “x” is the element and “y” is the sequence where membership is being checked.
“ x”是元素,“ y”是检查成员资格的顺序。
Here is a simple program to show the usage of Python in operator.
这是一个简单的程序,用于显示运算符中Python的用法。
vowels = ['A', 'E', 'I', 'O', 'U']
ch = input('Please Enter a Capital Letter:\n')
if ch in vowels:
print('You entered a vowel character')
else:
print('You entered a consonants character')
Recommended Readings: Python input(), Python List
推荐读物 : Python input() , Python列表
We can use the “in” operator with Strings and Tuples too because they are sequences.
我们也可以对字符串和元组使用“ in”运算符,因为它们是序列。
>>> name='JournalDev'
>>> 'D' in name
True
>>> 'x' in name
False
>>> primes=(2,3,5,7,11)
>>> 3 in primes
True
>>> 6 in primes
False
我们可以在字典中使用Python“ in”运算符吗? (Can we use Python “in” Operator with Dictionary?)
Let’s see what happens when we use “in” operator with a dictionary.
让我们看看将“ in”运算符与字典一起使用会发生什么情况。
dict1 = {"name": "Pankaj", "id": 1}
print("name" in dict1) # True
print("Pankaj" in dict1) # False
It looks like the Python “in” operator looks for the element in the dictionary keys.
看起来像Python的“ in”运算符在字典键中寻找元素。
Python“不在”运算符 (Python “not in” Operator)
It’s opposite of the “in” operator. We can use it with sequence and iterables.
它与“ in”运算符相反。 我们可以将其与sequence和iterables一起使用。
>>> primes=(2,3,5,7,11)
>>> 6 not in primes
True
>>> 3 not in primes
False
翻译自: https://www.journaldev.com/38028/python-in-and-not-in-membership-operators
python 成员运算符