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

时间:2013-11-04 20:35:23

标签: python loops comparison nested

    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

我的代码应该将句子的字母数增加2. ex:a-> c,l-> n 我把print(“hi”)语句用于检查if语句是否曾被评估为真,但它永远不会。有人可以告诉我为什么吗?

4 个答案:

答案 0 :(得分:5)

is检查对象身份。由于您似乎正在测试两个字符串是否具有相同的值(不是相同的对象),因此==可以更好地为您服务。例如:

if inputlist[x] == alphabet[y]

您也可以为其他if语句进行相同的更新。

答案 1 :(得分:4)

问题是is比较了身份而不是字符串的相等性。两个相等的短字符串可能是相同的,因为CPython有一些字符串实习,但你通常不应该基于这种行为。相反,使用==来比较字符串的相等

请注意,您可以使用str.translate创建地图,并使用str.maketrans创建的地图:

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

您可以进一步使用string.ascii_lowercase,这样您就不需要自己输入字母了;或使用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!)'

答案 2 :(得分:1)

除了is精简之外,您的代码还有另一个问题:

只要y == 24,它就会中断:首先,a将被添加,然后alphabet[26] - 这会导致错误。

所以将你的逻辑改为

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]

这甚至可以进一步改善:

如果你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)]

答案 3 :(得分:0)

这可能有助于清除“是”关键字。 “是”检查对象标识,而不是值。

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)))

输出:

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

所以,这三个都有相同的值,但只有1和3是相同的。