python的list[]和list1{}

如题,请问大佬们list1[1,2,3,]和list2{1,2,3}有区别吗

 

python语言本身有4种基本的数据结构: 列表, 字典, 元组, 集合, 各有自己的特点, 一般列表和字典用的居多:

- 列表(list) :中括号

- 字典(dict) :大括号,里面元素成对 

- 元组(Tuple) :逗号

- 集合(set): 大括号

# 列表
ls1 = [1,2,3,4,5]
print(ls1)
# 字典
dic1 = {'A':1,'B':2}
print(dic1)
# 元组
tup1 = 4,5,6,7
print(tup1)
# 集合
s1 = set([2,2,2,1,3,3,'a','a'])
print(s1)

#输出
[1, 2, 3, 4, 5]
{'A': 1, 'B': 2}
(4, 5, 6, 7)
{'a', 1, 2, 3}

了解更多, 可参考:

https://blog.csdn.net/muyashui/article/details/111054052

A  = [1, 2, 3]
B  = {1, 2, 3}

print(A)
print(B)

print(type(A))
print(type(B))

print(A[1])
print(B[1])

 

[1, 2, 3]
{1, 2, 3}
<class 'list'>
<class 'set'>
2
Traceback (most recent call last):
  File "D:\prj\py_t\11.py", line 11, in <module>
    print(B[1])
TypeError: 'set' object is not subscriptable
>>> 

 

看明白了吗?一个是列表一个是集合,数学上对列表和集合的定义一样不?列表有序集合无需。