python - 一个非常短的代码,但 python 中的语法无效?

标签 python syntax

def decode(string):
    L=float(string[0])
    if (L==4):
        messageFrom4=[[string[0::L], string[1::L], string[2::L], string[3::L]]
        return messageFrom4
    if L!=4:
        return messageFrom4[0:L]

第二个返回被突出显示,“无效语法错误”是它不会运行的问题。

最佳答案

这一行有一个额外的 [ 导致了问题:

messageFrom4=[[string[0::L], string[1::L], string[2::L], string[3::L]]
              ^
             here

试试这个,注意 L 如果要用作切片索引则必须是整数,使用 else 是个更好的主意如果条件互斥:

def decode(string):
    L=int(string[0])
    if L==4:
        messageFrom4=[string[0::L], string[1::L], string[2::L], string[3::L]]
        return messageFrom4
    else:
        return string[0:L]

关于python - 一个非常短的代码,但 python 中的语法无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112204/

相关文章:

python - 如何保护 Django 中的对象不被删除?

syntax - 了解在 Rust 中使用 '*' 取消引用

C 结构函数语法 - 传递元素,返回结构

c - C中有多少个expr_no_commas '=' expr_no_commas表达式?

haskell - 如何在 Haskell 中将 "unpack"列表作为单个参数?

python - 将字典的字典(大小未知)写为矩阵

python - Airflow - 如何从上次成功的实例运行中执行 DAG?

python - Django View : Either save(update) all objects or None of them

python - 从路径 python 中提取 Json 值

c# - 如何在 C# 的 getter 和 setter 方法中进行验证?