【问题标题】:Python - Iterate through a list, swapping alphbets by indexes?Python - 遍历列表,按索引交换字母?
【发布时间】:2017-03-23 04:52:11
【问题描述】:

我需要编写一个代码,让字母通过 2 个列表旋转。

所以我需要定义一个函数,比如说它叫做rotate_text。

传递了2个参数,1个是字符串,1个是整数。

这是我目前的代码:

def rotate_text(text, n):
plaintext = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
ciphertext = ['FGHIJKLMNOPQRSTUVWYXZABCDE']
rotated_text = []
for i in plaintext:
    rotated_text = ciphertext[plaintext[i + n]]
result = ''.join(rotated_text)
return result

所以它需要做的是,如果我将 ABC 作为参数文本,将 2 作为参数 n,

A 应该返回 CDE 作为结果。或者 DOG 和 11 应该返回 OBK。我真的不认为我需要那个密文列表,所以我想我会把它拿出来,但是我该如何让这段代码工作呢?

如果程序得到 ABC 作为文本,它应该从明文列表中找到 A 的索引并 + n 到该索引,并从明文列表中找到满足加 n 索引的字母,然后......我很头疼.

谁能帮忙?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    这段代码怎么样? text 只能是大写字符。

    def rotate_text(text, n):
        for i in len(text):
            number = ord(text[i]) - ord('A')
            number = (number + n) % 26
            text[i] = chr(number + ord('A'))
        return text
    

    如果你也想使用小写,你应该使用if 语句。

    【讨论】:

    • 它在行号 = (number + n) % 26 处出错。它说的语法无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 2017-05-19
    相关资源
    最近更新 更多