python笔记_4_集合数组

1、集合数据类型

列表(List)有序、可更改、允许重复

元组(Tuple)有序、不可更改、允许重复

集合(Set)无序、无索引、不允许重复

词典(Dictionary)无序、可变、有索引、不允许重复

构造函数:

list1 = list(("aa","bb"))

set1 = set(("aa","bb"))

tuple1 = tuple(("aa","bb"))

dict1= dict(dict2)

thisdict = dict(brand="Porsche", model="911", year=1963)

# 请注意,dict()使用了等号而不是冒号来赋值

2、列表(List)

(1)列表用方括号编写

thislist = ["apple", "banana", "cherry"]

(2)索引

thislist[0]第一个

thislist[-1]最后一个

thislist[a:b]包括a不包括b

(3)遍历

for x in thislist:

print(x)

(4)判断是否存在

if "apple" in thislist:

(5)方法

长度:len(thislist)

添加到末尾:thislist.append("aaa")

添加到指定索引:thislist.insert(0,"aaa")

删除成员:thislist.remove("aaa")

删除末尾:thislist.pop()

删除指定索引:del list[0]

删除列表:del list

清空列表:thislist.clear()

复制列表:

list2=list1(同一个对象)

list2 = list1.copy()(新对象)

list2 = list(list1)(新对象)

合并列表+、extend:

list3=list1+list2

list1.extend(list2)

颠倒顺序:reverse()

排序:sort()

返回索引值:index()

返回具有指定值的元素数量:count()

3、元组(Tuple)

(1)元组是用圆括号编写的

thistuple = ("apple", "banana", "cherry")

(2)更改元组值

元组值不能修改

将元组转换为列表,更改列表,然后将列表转换回元组

y = list(x)

修改y

x = tuple(y)

(3)创建单项元组

需要添加一个逗号

thistuple = ("apple",)

(4)删除

必须是整个元组,元组不可改

del thistuple

(5)合并+

(6)count(),index()

4、集合(Set)

(1)集合用花括号编写

thisset = {"apple", "banana", "cherry"}

(2)添加

thisset.add("aaa")

thisset.update(["orange", "mango", "grapes"])添加多个

(3)删除

thisset.remove("aaa")必须存在aaa

thisset.discard("aaa")

pop()因为无序,随机删除,会返回被删对象

del thisset整个集合

(4)合并

set3 = set1.union(set2)

set1.update(set2)

5、字典(Dictionary)

(1)用花括号编写,拥有键和值

thisdict = {

  "brand": "Porsche",

  "model": "911",

  "year": 1963

}

(2)根据键取值

x = thisdict["model"]

x = thisdict.get("model")

(3)修改

thisdict["year"] = 2019

(4)只遍历键或值

keys()或values()

for x in thisdict.values():

(5)遍历键和值

for x, y in thisdict.items():

(6)删除

thisdict.pop("model")

del thisdict["model"]

删除最后一键值对thisdict.popitem()(在 3.7 之前的版本中,删除随机项目)

清空thisdict.clear()

(7)可嵌套

(8) 返回指定键的值。

如果该键不存在,则插入具有指定值的键。

setdefault()

posted @ 2022-01-18 10:26  LuLuYaa  阅读(42)  评论(0编辑  收藏  举报