在本文中,我们将学习python中的4种内置数据结构,即列表,字典,元组和集合。
列表是元素的有序序列。它是非标量数据结构,并且本质上是可变的。与存储属于相同数据类型的元素的数组相比,列表可以包含不同的数据类型。
通过将索引括在方括号中,可以借助索引来访问列表。
现在,让我们看一下插图以更好地了解列表。
lis=['nhooo',786,34.56,2+3j] # displaying element of list for i in lis: print(i) # adding an elements at end of list lis.append('python') #displaying the length of the list print("长度os列表是:",len(lis)) # removing an element from the list lis.pop() print(lis)
输出结果
nhooo 786 34.56 (2+3j) 长度os列表是: 5 ['nhooo', 786, 34.56, (2+3j)]
它也是Python中定义的非标量类型。就像列表一样,它也是字符的有序序列,但是元组本质上是不可变的。这意味着此数据结构不允许进行任何修改。
元素可以是用括号内的逗号分隔的异质或同质性质。
让我们看一个例子。
tup=('nhooo',786,34.56,2+3j) # displaying element of list for i in tup: print(i) # adding elements at the end of the tuple will give an error # tup.append('python') # displaying the length of the list print("长度os元组是:",len(tup)) # removing an element from the tup will give an error # tup.pop()
输出结果
nhooo 786 34.56 (2+3j) 长度os元组是: 4
它是对象的无序集合,没有任何重复。这可以通过将所有元素括在花括号内来完成。我们还可以通过关键字“ set”使用类型转换来形成集合。
一组元素必须是不可变的数据类型。Set不支持索引,切片,串联和复制。我们可以使用索引对元素进行迭代。
现在让我们看一个例子。
set_={'tutorial','point','python'} for i in set_: print(i,end=" ") # print the maximum and minimum print(max(set_)) print(min(set_)) # print the length of set print(len(set_))
输出结果
tutorial point python tutorial point 3
字典是键值对的无序序列。索引可以是任何不可变的类型,称为键。在花括号中也指定了该选项。
我们可以借助与它们关联的唯一键来访问这些值。
让我们来看一个例子。
# Create a new dictionary d = dict()# Add a key - value pairs to dictionary d['tutorial'] = 786 d['point'] = 56 # print the min and max print (min(d),max(d)) # print only the keys print (d.keys()) # print only values print (d.values())
输出结果
point tutorial dict_keys(['tutorial', 'point']) dict_values([786, 56])
在本文中,我们了解了Python语言中存在的内置数据结构及其实现。