-
紫衣仙女
您缺少一些字母,例如N。请注意,这{"M": "N"}与 不同{"N": "M"}。话虽如此,您甚至不需要字典,就好像您从 155 (65+65+26-1) 中减去大写字母的ASCII 代码(例如 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'
-
慕的地8271018
根据您提供的代码,我发现以下奇怪之处: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_chprint(toret)如果您没有定义所有可能字符的对应项,那么使用字典的get(k)方法是明智的,该方法在未找到键k时返回None 。必须考虑到get(k)方法有默认返回值参数,以防找不到键,因此您可以使用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(...)我们将列表转换回字符串。
-
largeQ
如果您确实想使用一个字典,其中每个键“字母”都有值“相反字母”:这是一个可能的解决方案: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'}