为什么这些代码行在python中是合法的?

2024-05-15 17:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:这个问题似乎与列表切片和使用错误代码相混淆。进一步澄清了这个问题。你知道吗

我想问一下下面两行代码在python中的字面意思是什么。你知道吗

In [51]: data = list(range(10))                                                                              
In [53]: data[-1]   

背景

我无意中通过python语法检查器(pylint)运行了上述原始Jupyter笔记本输出,令人惊讶的是,它没有抛出语法错误,而是

In [53]: data[-1]  
   ^ (bad-whitespace)
code2.py:1:0: C0111: Missing module docstring (missing-docstring)
code2.py:1:0: E0602: Undefined variable 'In' (undefined-variable)
code2.py:1:9: E0602: Undefined variable 'data' (undefined-variable)
code2.py:2:0: E0602: Undefined variable 'In' (undefined-variable)
code2.py:2:9: E0602: Undefined variable 'data' (undefined-variable)

------------------------------------------------------------------------
Your code has been rated at -115.00/10 (previous run: -90.00/10, -25.00)

所以我试着理解那些代码行实际上在做什么。你知道吗

我试着插入缺失的变量。你知道吗

在这里我得到了下面的结果,看起来像是一个字典赋值。你知道吗

In = {}
data = ['apple'] # This list needed values, otherwise data[-1] threw an error

In [51]: data = list(range(10))                                                                              
In [53]: data[-1] 

print(In)    # {51: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}

# Why were there no values for key 53? (either {53: 'apple'})

我真的不明白这两行代码是怎么回事。你知道吗

我不认为这行代码是合法的In [51]: data = list(range(10)),既然是这样,为什么In [53]值在那之后就没有赋值呢?你知道吗

因此,任何对参考文献的解释或指导都将不胜感激。非常感谢。你知道吗


Tags: 代码inpyappledatarangevariablelist
2条回答

你从不给它赋值

In [53]

你只要查字典的这部分就行了。如果你这样做,条目就会出现在dict中

In[53]: data[-1] = 'hello world'

Result: {51: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 53: 'hello world'}

会回答这个问题,以防有人问我同样的问题。你知道吗

感谢@Goyo为我指出了python3.6中引入的Variable Annotations

variable: annotation = assignment

与使用注释(fruit: str = 'apple'vsfruit = 'apple' # type: str)相比,此语法用于注释变量中的类型。你知道吗

注释字段中的值没有严格执行,这就是语法合法的原因。你知道吗

第一次陈述

In [51]: data = list(range(10))

Variable = In [51] 
Annotation = data
Assignment = list(range(10))  

第二次陈述

In [53]: data[-1]

Variable = In [53]
Annotation = data[-1]

相关问题 更多 >