繁体   English   中英

为什么如果没有 if 语句的 else 块,这段代码就不能工作? - Python

[英]Why isn't this code working without an else block to the if statement? - Python

第一次在这里发帖:)

所以我想要实现的是,如果在“键”列表中的列表中找到一个字符,则将该列表中的“其他”字符添加到变量“s”中。 如果在列表中找不到字符,则将字符本身添加到变量“s”中。

message="hello !"
s=""
found=False
key=[['m', 'c'], ['u', 'e'], ['b', 'g'], ['a', 'k'], ['s', 'v'], ['h', 'x'],['i', 'z'], ['r', 'y'], ['p', 'w'], ['l', 'n'], ['o', 'j'], ['t', 'f'], ['q', 'd']]
for i in message:
    for j in key:
        if i==j[0]:
            found=True
            s+=j[1]
            break
        elif i==j[1]:
            found=True
            s+=j[0]
            break
    if not found:
        s+=i
return s

输入:

hello !

预期 output:

xunnj !

不知何故,后面的部分(将字符本身添加到 's' 变量)不起作用,除非我在第一个 if 语句中放置一个 else 块。 像这样,

if i==j[0]:
        found=True
        s+=j[1]
        break
elif i==j[1]:
        found=True
        s+=j[0]
        break
else:
        found=False

output 没有 else 块:

xunnj

我想知道为什么,

if not found:
        s+=i

如果没有第一个 if 语句的 else 块,则不起作用 谢谢。

每次进入内部循环时都需要给found = False ,否则它只会从所有循环的外部设置found = False一次,这就是为什么如果在内部循环中的任何时间found变为True那么它永远不会变为对于当时的 rest 来说是False的并且仍然是True ,这就是为什么if not found:因为found的东西总是True

你的代码应该是这样的:

message="hello !"
s=""
# found=False 
key=[['m', 'c'], ['u', 'e'], ['b', 'g'], ['a', 'k'], ['s', 'v'], ['h', 'x'],['i', 'z'], ['r', 'y'], ['p', 'w'], ['l', 'n'], ['o', 'j'], ['t', 'f'], ['q', 'd']]
for i in message:
    found=False  # use found here, cause you need to give `found = False` every time you enter in the inner loop, as in the inner loop you are considering found every time, so you need to set it from the outer loop
    for j in key:
        if i==j[0]:
            found=True
            s+=j[1]
            break
        elif i==j[1]:
            found=True
            s+=j[0]
            break
    if not found:
        s+=i
print(s) # you may be want to print the `s` rather return

Output:

xunnj !

使用dict更简单,并且dict很容易创建给定的可迭代列表,如key

>>> d = dict(key)
>>> d.update(map(reversed, key))
>>> ''.join(d.get(x, x) for x in message)
'xunnj !'

暂无
暂无

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

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