简体   繁体   English

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

[英]Storing unique string using if no in == False

writing a simple code to store unique string into list .编写一个简单的代码将唯一的字符串存储到list However if i use if var in list == False the string output = blank .但是,如果我使用if var in list == False字符串 output = blank However if i use If var not in list , I gotten the desired output.但是,如果我使用If var not in list ,我得到了所需的 output。

please advise why if var in list == False does not work here.请告知为什么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)

Its a bit subtle but its because of Comparison chaining .它有点微妙,但它是因为比较链接 Comparitors < | > | == | >= | <= | != | is [not] | [not] in比较器< | > | == | >= | <= | != | is [not] | [not] in < | > | == | >= | <= | != | is [not] | [not] in < | > | == | >= | <= | != | is [not] | [not] in have equal prescience and are compared left to right. < | > | == | >= | <= | != | is [not] | [not] in具有同等的预见性并从左到右进行比较。 In addition, chaining of the operations is the same as adding an "and".此外,操作的链接与添加“and”相同。 The familiar example is:熟悉的例子是:

x < y <= z is equivalent to x < y and y <= z . x < y <= z等价于x < y and y <= z

The same holds for in .对于in如此。 Your expression is the same as你的表达方式和

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

Your working example if word in bank: is the canonical way of writing the expression... no need to make it complicated!您的工作示例if word in bank:是编写表达式的规范方式......无需使其复杂!

@tdelaney gave the correct above. @tdelaney 上面给出了正确的答案。 Here is how you would write it:以下是您的编写方式:

if word not in bank:
  bank.append()

Or even better use a set instead of a list.或者甚至更好地使用集合而不是列表。

bank = set()
while True:
  word = input('Enter a word,type"done"to finish')
  if word == 'done':
    break
  bank.add(word)

bank = list(bank)
bank.sort()
print(bank);

Your code doesn't work because it represents it like:您的代码不起作用,因为它表示如下:

if word in (bank == False):

It's like the order of operations in math, so it takes it first processes whether bank is False , not processing first whether word is in bank , so if you use parenthesis, it would work:这就像数学中的运算顺序,所以它首先处理bank是否为False ,而不是首先处理word是否在bank中,所以如果你使用括号,它会起作用:

if (word in bank) == False:

If you change it to the above ^, it would work.如果你把它改成上面的^,就可以了。

But of course it's more recommended if you use:但当然,如果您使用以下方法,则更推荐:

if word not in bank:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM