Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 本命令的解释_Python_Python 3.x - Fatal编程技术网

Python 本命令的解释

Python 本命令的解释,python,python-3.x,Python,Python 3.x,我对python非常陌生,主要来自R语言编程。在学习过程中,我遇到了这段代码 xs=[()] res=[False]*2 if xs: res[0]= True if xs[0]: res[1]=True print(res) 起初我认为这是一种初始化空数组的方法。但是,当我运行相同的代码段,用空列表替换初始化部分时,它会给我一个错误 xs=list() res=[False]*2 if xs: res[0]= True if xs[0]: res[1]=Tru

我对python非常陌生,主要来自R语言编程。在学习过程中,我遇到了这段代码

xs=[()]
res=[False]*2
if xs:
    res[0]= True
if xs[0]:
    res[1]=True
print(res)
起初我认为这是一种初始化空数组的方法。但是,当我运行相同的代码段,用空列表替换初始化部分时,它会给我一个错误

xs=list()
res=[False]*2
if xs:
    res[0]= True
if xs[0]:
    res[1]=True
print(res)
有人能帮我理解这两种代码之间的区别吗。感谢您的帮助。谢谢

首先

xs=[()] <---------
第二

xs = list()
意味着

所以


问题的基础是两个列表定义,考虑代码:

xs1 = [()]   # create a list with a single element, which is an empty tuple
xs2 = list() # create an empty list

xs在您的第一个代码块中有一个元素(空列表),因此它可以工作。在第二个代码块中,xs确实是空的(没有元素),因此代码失败,因为xs[0]不存在。

这里xs是一个空列表,您试图调用xs[0],这是不可能的,因此它显示了一个错误。。在最初的例子中,xs是一个以空元组作为元素的列表。它们都应该初始化空数组,但其中一个会抛出错误,而另一个不会。是的,但索引0的对象是空元组,因此在这两种情况下都有一些内容,只需打印
len(xs)
,您就会看到问题。你不能索引空序列(至少不是这样)。那么这是否意味着我可以访问元组的任何假设索引,即使它没有初始化?@Mohit-不,相反,你只能在它存在时访问它。这种解释令人困惑,因为xs的第一个元素(即xs[0])本身就是一个空元素。xs[0]=>()
xs = []
xs[0] # does not xsist
xs1 = [()]   # create a list with a single element, which is an empty tuple
xs2 = list() # create an empty list