一.字典
字典是无序的、可变的,其内容是以"键-值对"的形式存储的。
主要特征:
1) 通过键而不是通过索引来读取
2)字典是任意对象的无序集合
3)字典是可变的,并且可以任意嵌套
4)字典中的键必须唯一
5) 字典中的键必须不可变,即字典中的键是不可变的,所以可以使用数字、字符串或者元组,但不能使用列表。
①字典的创建与删除
(1)用赋值表达式创建字典
dictionary = {'key1':'value1', 'key2':'value2',...,'keyn':'valuen'}
(2)通过映射函数创建字典
dictionary = dict(zip(list1,list2))
name = ['绮梦', '黄某'] sign = ['水瓶座', '天狗座'] dictionary = dict(zip(name, sign)) print(dictionary)
(3)通过给定的键值对创建字典
dictionary = dict(key1 = value1, key2 = value2,...,keyn = valuen)
dictionary = dict(绮梦='水瓶座', 黄某='天狗座') print(dictionary)
②访问字典
print(dictionary)
此外,python推荐的方法是使用对象的get()方法获取指定键的值。
dictionary.get(ket[,default])
default是可选项,用于当指定的键不存在时,返回一个默认值,如果省略,则返回None
③遍历字典
获取字典的"键值对"列表:
dictionary.items()
通过for循环遍历:
dictionary = {'黄某': 5438, '石某': 6666} print(dictionary) for item in dictionary.items(): print(item)
④添加、修改和删除字典元素
添加字典元素:
dictionary[key] = value
举例:
# -- coding: utf-8 -- dictionary = dict((('绮梦', '水瓶座'), ('黄某', '天牛座'))) dictionary['碧落'] = "巨蟹座" print(dictionary)
修改字典元素
# -- coding: utf-8 -- dictionary = dict((('绮梦', '水瓶座'), ('黄某', '天牛座'))) dictionary['黄某'] = "天狗座" # 添加一个元素,当元素存在时,则相当于修改功能 print(dictionary)
删除字典元素
# -- coding: utf-8 -- dictionary = dict((('绮梦', '水瓶座'), ('黄某', '天牛座'))) del dictionary["黄某"] print(dictionary)
⑤字典推导式
import random randomdict = {i: random.randint(10, 100) for i in range(1, 5)} print("生成的字典为", randomdict)
二.集合
Python中的集合(set)用于保存不重复的元素。它有可变集合set和不可变集合frozenset
两种。
①创建集合
(1)直接使用{}创建集合
setname = {element 1, element 2, element 3,...,element n}
举例:
set1 = {3,1,4,5,6,7} set2 = {'Python',27}
(2)使用set()函数创建集合
setname = set(iteration)
举例:
set1 = {1,5,8,3,6,9}
②添加元素
添加元素时,可以使用add()方法
setname.add(element)
举例:
a = {'黄某人'} a.add('长得帅') print(a)
③删除元素
可以使用del语句删除整个集合,也可以使用集合的pop()方法和remove()方法删除一个元素,还可以使用集合对象的clear()方法清空集合(变为空集合)
a = (['黄某人', '石某人']) a.remove('黄某人') print(a) b = (['黄某人', '石某人']) b.clear() print(b)
④集合的交集、并集和差集运算
a = set(['黄某人', '石某人']) b = set(['黄某人', '石某人']) print('交集运算:', a & b) print('并集运算:', a|b) print('差集运算:', a-b)