Python:[]在这里的含义是什么? [英] Python: What does the use of [] mean here?
问题描述
这两个在python中的语句有什么区别?
What is the difference in these two statements in python?
var = foo.bar
和
var = [foo.bar]
我认为这使var成为包含foo.bar的列表,但是我不确定.另外,如果这是行为,并且foo.bar已经是列表,您在每种情况下会得到什么?
I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?
例如:如果foo.bar = [1、2],我会得到这个吗?
For example: if foo.bar = [1, 2] would I get this?
var = foo.bar #[1, 2]
和
var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list
推荐答案
[]
是一个空列表.
[foo.bar]
正在创建一个新列表([]
),其中foo.bar
作为列表中的第一项,然后可以通过其索引进行引用:
[foo.bar]
is creating a new list ([]
) with foo.bar
as the first item in the list, which can then be referenced by its index:
var = [foo.bar]
var[0] == foo.bar # returns True
因此,您猜测foo.bar = [1,2]
的分配是完全正确的.
So your guess that your assignment of foo.bar = [1,2]
is exactly right.
如果您还没有的话,我建议您在Python交互式解释器中尝试这种事情.这很容易:
If you haven't already, I recommend playing around with this kind of thing in the Python interactive interpreter. It makes it pretty easy:
>>> []
[]
>>> foobar = [1,2]
>>> foobar
[1, 2]
>>> [foobar]
[[1, 2]]
这篇关于Python:[]在这里的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!