Hao*_*hen 55 python syntax curly-braces square-bracket
python中花括号和方括号之间有什么区别?
A ={1,2}
B =[1,2]
Run Code Online (Sandbox Code Playgroud)
当我打印A和B我的终端上,他们并没有区别.这是真的吗?
有时,我注意到一些代码使用{}并[]初始化不同的变量.
例如A=[],B={}
那有什么区别吗?
Mar*_*ers 82
他们被称为文字 ; 一套文字:
aset = {'foo', 'bar'}
Run Code Online (Sandbox Code Playgroud)
或字典文字:
adict = {'foo': 42, 'bar': 81}
empty_dict = {}
Run Code Online (Sandbox Code Playgroud)
或列表文字:
alist = ['foo', 'bar', 'bar']
empty_list = []
Run Code Online (Sandbox Code Playgroud)
要创建空集,您只能使用set().
集合是唯一元素的集合,您无法对它们进行排序.列表是有序的元素序列,可以重复值.字典将键映射到值,键必须是唯一的.集合和字典键也必须满足其他限制,这样Python实际上可以有效地跟踪它们,并且知道它们是并且将保持唯一.
还有一个tuple类型,使用逗号表示一个或多个元素,在许多上下文中括号是可选的:
atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')
Run Code Online (Sandbox Code Playgroud)
注意another_tuple定义中的逗号; 是逗号使它成为一个tuple,而不是括号.WARNING_not_a_tuple它不是一个元组,它没有逗号.没有括号,你剩下的只是一个字符串.
有关更多详细信息,请参阅Python教程的数据结构一章 ; 列表在介绍章节中介绍.
诸如这些容器的文字也称为显示,并且语法允许基于循环,称为理解来程序地创建内容.
Dae*_*yth 10
他们创造不同的类型.
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
>>> type({1, 2})
<type 'set'>
>>> type({1: 2})
<type 'dict'>
>>> type([1, 2])
<type 'list'>
Run Code Online (Sandbox Code Playgroud)