【问题标题】:Print key and if conditional is met print key value打印键,如果满足条件,则打印键值
【发布时间】:2020-10-15 07:28:40
【问题描述】:

我想创建简单的“编码脚本”。

我有这本词典:

diction =  {
"A" :  "Z", 
"Y" :  "B",
"C" :  "X"
}

我想给出一些随机句子,遍历它的字母,如果在这本词典中找到字母 - 打印相反的字母
所以,如果我说的话

"ABC"

它应该返回:

"ZYX"

我试过这段代码,但我有一个“KeyError”:

# Defining dictionary
diction =  {
"A" :  "Z", 
"Y" :  "B",
"C" :  "X",
"W" :  "E",
"E" :  "V",
"U" :  "F",
"G" :  "T",
"S" :  "H",
"I" :  "R",
"Q" :  "J",
"K" :  "P",
"O" :  "L",
"M" :  "N",
" " :  " "
}

# Sentence in "szyfr" variable should be split into list.

szyfr = "SOME SENTENCE WHATEVER"

def split(szyfr): 
     return [char for char in szyfr]

szyfr = split(szyfr)


# Now I want to iterate through "szyfr" and replace letters as in "CAT" example:  

for i in szyfr:
        if i in diction:
                
                diction = {x:y for x,y in diction.items()}
                print(i)
                print("Variable: " + i + " is in 'key'")
                pass
        elif diction[i] in szyfr:
                diction = {y:x for x,y in diction.items()}
                print(i)
                print("Variable: " + i + " is in 'value'")
        elif i is " ":
                pass

print(szyfr)

【问题讨论】:

  • 你为什么在你的循环中改变diction

标签: python python-3.x dictionary if-statement


【解决方案1】:

您缺少一些字母,例如N。请注意,{"M": "N"}{"N": "M"} 不同。

话虽如此,您甚至不需要字典,就像从 155 (65+65+26-1) 中减去大写字母的 ASCII code(例如 A 的 65)一样,您最终会得到对应字母的ASCII码:

>>> szyfr = "SOME SENTENCE WHATEVER"
>>> "".join(chr(155-ord(e)) if "A" <= e <= "Z" else e for e in szyfr)
'HLNV HVMGVMXV DSZGVEVI'

【讨论】:

    【解决方案2】:

    如果你真的想使用一个字典,其中每个键“字母”的值都是“相反的字母”:

    这是一个可能的解决方案:

    diction = {" ": " "}
    
    all_letters = range(ord('A'), ord('Z')+1)
    for char, opsite_char in zip(all_letters, reversed(all_letters)):
        diction[chr(char)] = chr(opsite_char)
    
    print(diction)
    

    输出:

    {' ': ' ', 'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U', 'G': 'T', 
    'H': 'S', 'I': 'R', 'J': 'Q', 'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L', 
    'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W': 'D', 
    'X': 'C', 'Y': 'B', 'Z': 'A'}
    

    【讨论】:

    • 更简单的方法:import string; d = dict(zip(string.ascii_uppercase, reversed(string.ascii_uppercase)))
    • 没错,但我想通过展示他们的ASCII之间的关系,它可能会帮助他意识到这个问题甚至不需要创建一个字典。万一问题不需要它。
    【解决方案3】:

    按照您提供的代码,我发现以下奇怪之处:

    szyfr = "SOME SENTENCE WHATEVER"
    
    def split(szyfr): 
         return [char for char in szyfr]
    
    szyfr = split(szyfr)
    

    您似乎正在尝试从字符串构建列表,这可以简单地完成为:

    >>> s = "hola"
    >>> l1 = list(s)
    >>> l1
    ['h', 'o', 'l', 'a']
    

    所以,在您的具体情况下:

    szyfr = "SOME SENTENCE WHATEVER"
    szyfr = list(szyfr)
    

    不过,它并不是真正需要的,因为您可以直接管理一个字符串,就像它是一个列表一样,使用 for

    现在,您想替换特定字典后面的字符。我发现您的解决方案过于复杂,而您只需要:

    diction =  {
    "A" :  "Z", 
    "Y" :  "B",
    "C" :  "X",
    "W" :  "E",
    "E" :  "V",
    "U" :  "F",
    "G" :  "T",
    "S" :  "H",
    "I" :  "R",
    "Q" :  "J",
    "K" :  "P",
    "O" :  "L",
    "M" :  "N",
    " " :  " "
    }
    
    sentence_to_code = input("Give me a sentence: ").strip().upper()
    toret = ""
    
    for ch in sentence_to_code:
        coded_ch = diction.get(ch)
    
        if not coded_ch:
            coded_ch = ch
    
        toret += coded_ch
    
    print(toret)
    

    如果您没有为所有可能的字符定义对应对象,那么使用字典的 get(k) 方法是明智的,该方法在 key 时返回 None k 没有找到。

    必须考虑到get(k)方法在没有找到key的情况下返回值有默认参数,所以可以使用get(k, default_return_value ),这让我们可以进一步简化代码:

    diction =  {
    "A" :  "Z", 
    "Y" :  "B",
    "C" :  "X",
    "W" :  "E",
    "E" :  "V",
    "U" :  "F",
    "G" :  "T",
    "S" :  "H",
    "I" :  "R",
    "Q" :  "J",
    "K" :  "P",
    "O" :  "L",
    "M" :  "N",
    " " :  " "
    }
    
    sentence_to_code = input("Give me a sentence: ").strip().upper()
    toret = "".join([diction.get(ch, ch) for ch in sentence_to_code])
    
    print(toret)
    

    现在我们使用列表推导,因为我们不再需要条件。调用diction.get(ch, ch) 返回ch 或相应的编码字符,或者如果在字典中没有找到ch 本身。通过调用str.join(),即"".join(...),我们将列表转换回字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多