简体   繁体   English

为什么我的if语句不比较列表项

[英]why is my if statement not comparing list items

    alphabet =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
def decoder(input):
    inputlist = list(input)
    inputlength = len(input)
    alphabetlength = len(alphabet)
    result = "Decoded Sentence: "
    for x in range(inputlength):
        for y in range(alphabetlength):
            if inputlist[x] is alphabet[y]:
                print ("hi")
                if y == 24:
                    result += "a"
                if y == 25:
                    result += "b"
                else:
                    result += alphabet[y+2]
            if inputlist[x] is "(":
                result += "("
            if inputlist[x] is ")":
                result += ")"
            if inputlist[x] is ".":
                result += "."
            if inputlist[x] is " ":
                result += " "
    return result

My code is supposed to increment a sentence's alphabets by 2. ex: a->c, l->n I put the print("hi") statement to check if the if-statement was ever evaluated to be true but it never does. 我的代码应该将一个句子的字母增加2。例如:a-> c,l-> n我放了print(“ hi”)语句来检查if语句是否曾经被评估为真,但从未如此。 。 Can someone please tell me why? 有人可以告诉我为什么吗?

is checks object identity . is检查对象标识 Since you appear to be testing whether two strings have the same value (not are the same object ), you would be better served by == . 由于您似乎正在测试两个字符串是否具有相同的值(不是同一对象 ),因此==会更好。 For example: 例如:

if inputlist[x] == alphabet[y]

You can make the same update for your other if statements as well. 您也可以对其他if语句进行相同的更新。

The problem is that is compares identity and not equality of strings. 问题是, is比较认同,而不是字符串的平等。 Two short strings that are equal may be identical due to some string interning CPython does, but you generally should not build on this behavior. 由于CPython进行了一些字符串内部插入,所以两个相等的短字符串可能是相同的,但通常不应以此行为为基础。 Instead, use == to compare the equality of strings. 而是使用==比较字符串的相等性。

Note, that you can do this a lot better using str.translate , with a map created by str.maketrans : 请注意,使用str.translate ,以及str.maketrans创建的映射,您可以str.maketrans

>>> table = str.maketrans('abcdefghijklmopqrstuvwxyz', 'cdefghijklmopqrstuvwxyzab')
>>> 'hello world'.translate(table)
'jgooq yqtof'

You can further use string.ascii_lowercase so you don't need to type the alphabet yourself; 您可以进一步使用string.ascii_lowercase因此您无需自己输入字母; or use string.ascii_letters for lower and upper case characters: 或将string.ascii_letters用作大小写字符:

>>> table = str.maketrans(string.ascii_letters, string.ascii_letters[2:] + string.ascii_letters[:2])
>>> 'Hello World (This works!)'.translate(table)
'Jgnnq Yqtnf (Vjku yqtmu!)'

Besides of the is thin, you have another problem in your code: 再说的is薄,你必须在你的代码的另一个问题:

As soon as y == 24 , it will break: First, a will be added and then alphabet[26] - which results in an error. 一旦y == 24 ,它会破坏:首先, a将被添加,然后alphabet[26] -这将导致一个错误。

So change your logic to 所以改变你的逻辑

for inp in inputlist:
    if inp in "(). ":
        result += inp
    else: # very important
        for y in range(alphabetlength):
            if inp == alphabet[y]:
                if y == 24:
                    result += "a"
                elif y == 25: # elif instead of if!
                    result += "b"
                else:
                    result += alphabet[y+2]

This can even improved further: 这甚至可以进一步改善:

If you make alphabet = 'abcdefghijklmnopqrstuvwxyz' , you can do 如果您使alphabet = 'abcdefghijklmnopqrstuvwxyz' ,则可以

for inp in inputlist:
    if inp in "(). ":
        result += inp
    else: # very important
        idx = alphabet.find(inp)
        if idx >= 0: # found
            result += alphabet[(idx + 2) % len(alphabet)]

This might help clear up the "is" keyword. 这可能有助于清除“ is”关键字。 "is" checks the object identity, not the value. “是”检查对象标识,而不是值。

var_1 = ('a', 'b')
var_2 = ('a', 'b') # same content, but different object
var_3 = var_1 # same object
n = lambda v: ' ' if v else ' not '
print('{0} has{2}the same value as {1}'.format('var_1', 'var_2', n(var_1 == var_2)))
print('{0} has{2}the same value as {1}'.format('var_2', 'var_3', n(var_2 == var_3)))
print('{0} has{2}the same value as {1}'.format('var_3', 'var_1', n(var_3 == var_1)))
print('{0} is{2}the same object as {1}'.format('var_1', 'var_2', n(var_1 is var_2)))
print('{0} is{2}the same object as {1}'.format('var_2', 'var_3', n(var_2 is var_3)))
print('{0} is{2}the same object as {1}'.format('var_3', 'var_1', n(var_3 is var_1)))

Output: 输出:

var_1 has the same value as var_2
var_2 has the same value as var_3
var_3 has the same value as var_1
var_1 is not the same object as var_2
var_2 is not the same object as var_3
var_3 is the same object as var_1

So, all three have the same value, but only 1 and 3 are identical. 因此,这三个值都相同,但是只有1和3相同。

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

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