python 圆括号和方括号一样吗_Python中花括号和方括号有什么区别?

what is the difference between curly brace and square bracket in python?

A ={1,2}

B =[1,2]

when I print A and B on my terminal, they made no difference. Is it real?

And sometimes, I noticed some code use {} and [] to initialize different variables.

E.g. A=[], B={}

Is there any difference there?

解决方案

Curly braces create dictionaries or sets. Square brackets create lists.

They are called literals; a set literal:

aset = {'foo', 'bar'}

or a dictionary literal:

adict = {'foo': 42, 'bar': 81}

empty_dict = {}

or a list literal:

alist = ['foo', 'bar', 'bar']

empty_list = []

To create an empty set, you can only use set().

Sets are collections of unique elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.

There is also the tuple type, using a comma for 1 or more elements, with parenthesis being optional in many contexts:

atuple = ('foo', 'bar')

another_tuple = 'spam',

empty_tuple = ()

WARNING_not_a_tuple = ('eggs')

Note the comma in the another_tuple definition; it is that comma that makes it a tuple, not the parenthesis. WARNING_not_a_tuple is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.

See the data structures chapter of the Python tutorial for more details; lists are introduced in the introduction chapter.

Literals for containers such as these are also called displays and the syntax allows for procedural creation of the contents based of looping, called comprehensions.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值