【问题标题】:invalid syntax in returning a list in python在 python 中返回列表时语法无效
【发布时间】:2020-10-26 18:23:18
【问题描述】:
def rotate_word(word,number):
    new_word_number=[]
    new_word=[]
    for letter in word:
        new_word_number.append(ord(letter)+number)
        new_word.append(chr(new_word_number))
    return new_word   
                        
        
rotate_word('xyz',2)

此代码显示错误 TypeError: an integer is required (got type list)

【问题讨论】:

  • 您在return 之前的行中缺少)。 VTC 是一个错字。
  • 新的TypeError是因为new_word_number是一个列表。

标签: python list return


【解决方案1】:

不知道你想要达到什么目的,但这里有一个可以工作的代码:

def rotate_word(word, number):
    new_word = []
    for letter in word:
        new_word.append(chr(ord(letter) + number))
    return ''.join(new_word)


print(rotate_word('xyz', 2))

将打印z{|

请注意,您不需要两个中间列表。 此外,使用''.join(your_list) 将允许将结果列表合并为一个字符串,以便您的函数返回与给定相同的类型。

顺便说一句,如果您最初的目标是实现像 rot13(在您的情况下为 rot2)这样的字符旋转,您可以使用更智能的函数,该函数也只处理字母字符以使输出可移植(仅可打印字符):

def rotX(string: str, shift: int = 13):
    """
    RotX for only A-Z and a-z characters
    """
    try:
        return ''.join(
            [chr(ord(n) + (shift if 'Z' < n < 'n' or n < 'N' else -shift)) if ('a' <= n <= 'z' or 'A' <= n <= 'Z') else n for
             n in
             string])
    except TypeError:
        return None

result = rotX('xyz', 2)
reverse_result = rotX(result, -2)
print(result)
print(reverse_result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-19
    • 2015-05-24
    • 2021-12-10
    • 2018-05-17
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多