容器:列表、元祖、字典、集合

集合

介绍

集合(set)是一种无序集,它是一组键的集合,不存储值•在集合中,重复的键是不被允许的。集合可以用于去除重复值•集合也可以进行数学集合运算,如并、交、差以及对称差等。•应用:去重。把一个列表变成集合,就自动去重了:set(列表名)关系测试。测试两组数据之前的交集、差集、并集等关系

定义方式:

使用set([])函数或者使用大括号{}需要注意的是,创建空集合,必须使用set(),而不是{},因为{}表示创建一个空的字典

	#第一种方式
 m = {
    
    1,2,3,4,5,6,7,8,9,"abcdefg","bdefgeh"}
  # 第二种方式
 n = set([1,2,3,4,5,6,7,8,9,"abcdefg","bdefgeh"])

去重


    list1 = [1,2,3,4,5,6,2,3,4,5,6,7,"a","b","c"]
    y = set(list1)
    x = list(y)
    print(x)

运算

  a = {
    
    1,2,3,4,5,6}
    b = {
    
    4,5,6,7,8,9}
    print(a-b)   # 集合差集
    print(a|b)   # 集合并集
    print(a&b)   # 集合交集
    print(a^b)   # 集合的对称差

字典

遍历字典

  • 第一种方法:XXX.key()
# 该方法会返回一个序列,序列中保存有字典的所有的键
dictionary = {
    
    "at":"857324d764f743da95b34be3c79ee1c8","rt":"ee424e06495242268f9918268bdbafb2"}

print(dictionary)
print(dictionary.keys())
for key in dictionary.keys():
    print(key,dictionary[key])
  • 第二种方法:xxx.values()
dictionary = {
    
    "at":"857324d764f743da95b34be3c79ee1c8","rt":"ee424e06495242268f9918268bdbafb2"}

print(dictionary)
# 该方法返回一个序列,序列中保存有字典的所有的值,
# 该方法只能遍历字典中所有的值,不能遍历键
print(dictionary.values())
for val in dictionary.values():
    print(val)
  • 第三种方法:xxx.items() :
dictionary = {
    
    "at":"857324d764f743da95b34be3c79ee1c8","rt":"ee424e06495242268f9918268bdbafb2"}

print(dictionary)
#  xxx.items() : 返回字典中所有的key = values 返回一个序列,序列中包含有双值子序列
print(dictionary.items())
for key, value in dictionary.items():
    print(key,"=", value)

猜你喜欢

转载自blog.csdn.net/Mwyldnje2003/article/details/112916162
今日推荐