python - 使用 if no in == False 存储唯一字符串

标签 python list

编写一个简单的代码来将唯一的字符串存储到list 中。但是,如果我使用 if var in list == False 字符串输出 = blank。但是,如果我使用 If var not in list,我会得到所需的输出。

请告知为什么 if var in list == False 在这里不起作用。

bank = list()

while True:
      word = input('Enter a word,type"done"to finish')

      if word == 'done': break

      if word in bank == False: # this code does't work as intended
            bank.append(word)

bank.sort()
print(bank)

最佳答案

它有点微妙,但它是因为 Comparison chaining .比较器 < | > | == | >= | <= | != | is [not] | [not] in具有相同的先见之明,并从左到右进行比较。此外,操作链接与添加“与”相同。熟悉的例子是:

x < y <= z is equivalent to x < y and y <= z.

同样适用于 in .你的表情和

if (word in bank) and (bank == False):
    ....

您的工作示例 if word in bank:是编写表达式的规范方式...无需使其复杂化!

关于python - 使用 if no in == False 存储唯一字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65473126/

相关文章:

python - 用python从列表中制作字典

r - 查找仅在 R 中的一行中出现的变量

python - Numpy 和带有大数组的内存

python - 使用 pandas 根据另一个数据帧的行值填充列值

python - 插入排序 Python

python - 为什么以下列表理解在 Python 中不起作用?

python - 单元测试中如何使用python Mock side_effect充当Class方法

python - 在 for 循环中使用 append 方法

c# - 两个列表同步

python - Python 无法正确识别字符串长度?