Python:这里使用[]是什么意思?
python中这两个语句有什么区别?
var = foo.bar
我
var = [foo.bar]
认为它正在将 var 放入包含 foo.bar 的列表中,但我不确定。另外,如果这是行为并且 foo.bar 已经是一个列表,那么在每种情况下你会得到什么?
例如:如果 foo.bar = [1, 2] 我会得到这个吗?
var = foo.bar #[1, 2]
和
var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list
What is the difference in these two statements in python?
var = foo.bar
and
var = [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?
For example: if foo.bar = [1, 2] would I get this?
var = foo.bar #[1, 2]
and
var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
[]
是一个空列表。[foo.bar]
正在创建一个新列表 ([]
),其中foo.bar
作为列表中的第一项,然后可以由其索引引用:所以您猜测您对
foo.bar = [1,2]
的分配是完全正确的。如果您还没有这样做,我建议您在 Python 交互式解释器中尝试一下这种事情。这使得事情变得非常简单:
[]
is an empty list.[foo.bar]
is creating a new list ([]
) withfoo.bar
as the first item in the list, which can then be referenced by its index:So your guess that your assignment of
foo.bar = [1,2]
is exactly right.If you haven't already, I recommend playing around with this kind of thing in the Python interactive interpreter. It makes it pretty easy:
是的,它正在创建一个包含一个元素 foo.bar 的列表。
如果 foo.bar 是
[1,2]
,您确实会得到 [[1,2]]。例如,
为了详细说明这个确切的例子,
Yes, it's making a list containing one element, foo.bar.
If foo.bar is
[1,2]
, you indeed get [[1,2]].For instance,
To elaborate a bit more on that exact example,
是的,它创建了一个新列表。
如果
foo.bar
已经是一个列表,它将简单地变成一个列表,包含一个列表。<前><代码>h[1]>>>> l = [1, 2]
h[1]>>>> [l]
[[1, 2]]
h[3]>>>>升[升][0]
[1, 2]
Yes, it creates a new list.
If
foo.bar
is already a list, it will simply become a list, containing one list.这几乎意味着它是一个数组/列表,其中 foo.bar 是列表/数组中的第一项。
That pretty much means it's an array/list of stuff with foo.bar being the first item in the list/array.