更多详情,可参考:alex大王第一周博客
list类型开始往后,更多详情,可参考:alex大王第二周博客
python3中,无论整数数值多大,都是int类型
更多详情,可参考:alex大王第二周博客
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
letters = ["a", "b", "c", "d", "e", "f"]
print("=========={title}==============".format(title="列表元素通过下标获取"))
# 列表元素通过下标获取
print(letters[0], letters[2])
print("=========={title}==============".format(title="切片"))
# 切片(相当于浅拷贝部分), 左闭右开[)
print(letters[1:3])
print(letters[-2:])
print(letters[:3])
# 切片时, 左边是开始截取下标, 右边是结束截取下标, 截取时方向为从左到右
print(letters[-1:-2])
print(letters[-1:])
# 切片时, 设置步长
print(letters[::3])
print("=========={title}==============".format(title="增加元素"))
# 增加元素
# append方法: 在list最后添加元素
print(letters.append("g"))
print(letters)
# insert方法: 通过指定下标, 往list中添加元素
print(letters.insert(0, "pangzi"))
print(letters)
print("=========={title}==============".format(title="修改元素"))
# 修改元素, 通过下标进行修改
letters[0] = "ejrghk"
print(letters)
print("=========={title}==============".format(title="删除元素"))
# 删除元素
# del方法: 1、通过指定list元素下标, 进行删除, 不能接收删除元素值; 也可以直接删除整个list
del letters[0]
print(letters)
# 删除letters
del letters
# 重新声明letters
letters = ["a", "b", "c", "d", "e", "f", "g"]
# pop方法: 通过指定list元素下标, 进行删除, 不指定下标, 默认为-1, 可以接收删除元素值
pop_item = letters.pop(-1)
print(pop_item)
print(letters)
print("=========={title}==============".format(title="获取元素下标"))
# 获取元素下标
print(letters.index("b"))
# 获取list中元素出现次数
print("=========={title}==============".format(title="获取list中元素出现次数"))
print(letters.count("b"))
print("=========={title}==============".format(title="list反转"))
# list反转
print(letters.reverse())
print(letters)
print("=========={title}==============".format(title="list排序"))
# list排序
print(letters.sort())
print(letters)
print("=========={title}==============".format(title="list合并"))
# list合并
nums = [1, 2, 3]
letters.extend(nums)
print(letters, nums)
print("=========={title}==============".format(title="list清除"))
# list清除
print(letters.clear())
print(letters)
# 输出:
==========列表元素通过下标获取==============
a c
==========切片==============
['b', 'c']
['e', 'f']
['a', 'b', 'c']
[]
['f']
['a', 'd']
==========增加元素==============
None
['a', 'b', 'c', 'd', 'e', 'f', 'g']
None
['pangzi', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
==========修改元素==============
['ejrghk', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
==========删除元素==============
['a', 'b', 'c', 'd', 'e', 'f', 'g']
g
['a', 'b', 'c', 'd', 'e', 'f']
==========获取元素下标==============
1
==========获取list中元素出现次数==============
1
==========list反转==============
None
['f', 'e', 'd', 'c', 'b', 'a']
==========list排序==============
None
['a', 'b', 'c', 'd', 'e', 'f']
==========list合并==============
['a', 'b', 'c', 'd', 'e', 'f', 1, 2, 3] [1, 2, 3]
==========list清除==============
None
[]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
letters = ("a", "b", "c", "d", "e", "f")
print("=========={title}==============".format(title="元组元素通过下标获取"))
print(letters.index("b"))
print("=========={title}==============".format(title="获取tuple中元素出现次数"))
print(letters.count("b"))
print("=========={title}==============".format(title="注意, 元组中只有一个元素时, 需要定义成如下格式"))
correct_tuple = ("a", )
incorrect_tuple = ("a")
print("正确的元组定义: 类型:{type}, 元组元素:{tuple}".format(type=type(correct_tuple), tuple=correct_tuple))
print("错误的元组定义: 类型:{type}, 元组元素:{tuple}".format(type=type(incorrect_tuple), tuple=incorrect_tuple))
print("=========={title}==============".format(title="注意, 元组中如果有list, list中的元素是可以改变的"))
tuple_contains_list = ("a", "b", ["c", "d"])
print("原始tuple:{original}".format(original=tuple_contains_list))
tuple_contains_list[-1].append("e")
print("修改tuple中list后:{after_modification}".format(after_modification=tuple_contains_list))
# 输出:
==========元组元素通过下标获取==============
1
==========获取tuple中元素出现次数==============
1
==========注意, 元组中只有一个元素时, 需要定义成如下格式==============
正确的元组定义: 类型:, 元组元素:('a',)
错误的元组定义: 类型:, 元组元素:a
==========注意, 元组中如果有list, list中的元素是可以改变的==============
原始tuple:('a', 'b', ['c', 'd'])
修改tuple中list后:('a', 'b', ['c', 'd', 'e'])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 在字符串中查找substring, 如果substring不存在, 返回-1, 如果存在, 则返回substring的开始下标, 多次出现时, 返回最左侧子串开始下标
print("find方法:%s" % sentence.find("name1"))
print("find方法:%s" % sentence.find("name"))
print("find方法:%s" % (sentence * 2).find("name"))
print_separator()
# 在字符串中查找substring, 如果substring不存在, 返回-1, 如果存在, 则返回substring的开始下标, 多次出现时, 返回最右侧子串开始下标
print("rfind方法:%s" % sentence.rfind("name1"))
print("rfind方法:%s" % (sentence * 2).rfind("name"))
# 输出:
原文:my name is Mason.
**************************************************
find方法:-1
find方法:3
find方法:3
**************************************************
rfind方法:-1
rfind方法:20
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 判断字符串是否以substring结尾
print("startswith方法:%s" % sentence.startswith("my"))
print("startswith方法:%s" % sentence.startswith("1my"))
print_separator()
# 判断字符串是否以substring结尾
print("endswith方法:%s" % sentence.endswith("Mason"))
print("endswith方法:%s" % sentence.endswith("Mason."))
# 输出:
原文:my name is Mason.
**************************************************
startswith方法:True
startswith方法:False
**************************************************
endswith方法:False
endswith方法:True
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# list转换为字符串, 使用字符串拼接list/tuple中的元素, 前提是list中元素必须为str类型, 否则无法拼接, 拼接完成后为新string
concatenation = ""
print(id(concatenation))
print(id(concatenation.join(["1", "2"])))
print("join方法:%s" % "".join(["1", "2", "3"]))
print("join方法:%s" % "_".join(["1", "2", "3"]))
# 输出:
1642662676080
1642670287728
join方法:123
join方法:1_2_3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
print_separator()
# 去字符串左边空格, 字符串中间的不去掉
print("lstrip方法:%s" % " \na bc".lstrip())
print_separator()
# 去字符串右边空格, 字符串中间的不去掉
print("rstrip方法:%s<<<" % "a bc\n\n ".rstrip())
print_separator()
# 去字符串左右边空格, 字符串中间的不去掉
print("strip方法:>>>%s<<<" % "\n\n a bc \n\n ".strip())
# 输出:
**************************************************
lstrip方法:a bc
**************************************************
rstrip方法:a bc<<<
**************************************************
strip方法:>>>a bc<<<
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 字符串中字符替换, 可以指定最多替换多少个字符
print("replace方法:%s" % "aaabc".replace("a", "A"))
print("replace方法:%s" % "aaabc".replace("a", "A", 2))
# 输出:
replace方法:AAAbc
replace方法:AAabc
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 字符串分割, 默认使用"空格"分割, 可以指定
print("split方法:%s" % "aaa bc".split())
print("split方法:%s" % "1+2+3+4".split("+"))
# 输出:
split方法:['aaa', 'bc']
split方法:['1', '2', '3', '4']
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
print_separator()
# 字符串变成小写
print("lower方法:%s" % "ABC".lower())
print_separator()
# 字符串变成大写
print("upper方法:%s" % "abc".upper())
# 输出:
**************************************************
lower方法:abc
**************************************************
upper方法:ABC
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 字符串转换为title格式, 所有单词首字母改成大写
print("title方法:%s" % sentence.title())
# 输出:
原文:my name is Mason.
**************************************************
title方法:My Name Is Mason.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 判断字符串中substring出现次数
print("count方法:%s" % sentence.count("a"))
print("count方法:%s" % sentence.count("Mason"))
# 输出:
原文:my name is Mason.
**************************************************
count方法:2
count方法:1
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# capitalize方法: str首字母改成大写
print("capitalize方法:%s" % sentence.capitalize())
# 输出:
原文:my name is Mason.
**************************************************
capitalize方法:My name is mason.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 格式化字符串:format方法(常用)、format_map方法(不常用)
print("format方法:%s" % "my name is {name} and I'm {age} years old.".format(name="Mason", age=25))
print("format_map方法:%s" % "my name is {name} and I'm {age} years old.".format_map({"name": "Mason", "age": 25}))
# 输出:
原文:my name is Mason.
**************************************************
format方法:my name is Mason and I'm 25 years old.
format_map方法:my name is Mason and I'm 25 years old.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
print_separator()
# 判断当前字符串所有字符是否均为大写, 否则返回False, 所有英文字符必须大写且至少有一个, 特殊字符/中文字符不管
print("isupper方法:%s" % "MY NAME IS".isupper())
print("isupper方法:%s" % "MY NAME Is".isupper())
print("isupper方法:%s" % "MY NAME IS !!#@二".isupper())
print("isupper方法:%s" % "".isupper())
print_separator()
# 判断当前字符串所有字符是否均为小写, 否则返回False, 所有英文字符必须小写且至少有一个, 特殊字符/中文字符不管, 与isupper刚好相反
print("islower方法:%s" % "my name is".islower())
print("islower方法:%s" % "my name IS".islower())
print("islower方法:%s" % "my name is !!#@二".islower())
print("islower方法:%s" % "".islower())
# 输出:
**************************************************
isupper方法:True
isupper方法:False
isupper方法:True
isupper方法:False
**************************************************
islower方法:True
islower方法:False
islower方法:True
islower方法:False
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 判断当前字符串, 如果字符串是标题大小写的字符串, 则返回True, 否则返回False, 需要是首字母大写, 一个单词只能首字母大写, 其余均小写, 不能为空
print("istitle方法:%s" % "My Name Is".istitle())
print("istitle方法:%s" % "My_Name_Is".istitle())
print("istitle方法:%s" % "My_#Name_Is".istitle())
print("istitle方法:%s" % "MyNameIs".istitle())
print("istitle方法:%s" % "".istitle())
# 输出:
istitle方法:True
istitle方法:True
istitle方法:True
istitle方法:False
istitle方法:False
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# center方法: 设置str长度, 设置填充字符, 长度缺少部分使用指定字符进行填充, 并将字符串放置于中间部分
print("center方法:%s" % sentence.center(50, '-'))
# 输出:
原文:my name is Mason.
**************************************************
center方法:----------------my name is Mason.-----------------
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
print_separator()
# 判断当前字符串是否为"字母+数字"组合, 排列顺序和字母大小写无影响, 不能为空字符串, 不能有除字母、数字外的符号
print("isalnum方法:%s" % "23aa".isalnum())
print("isalnum方法:%s" % "aa23".isalnum())
print("isalnum方法:%s" % "A23".isalnum())
print("isalnum方法:%s" % "A#23".isalnum())
print("isalnum方法:%s" % "".isalnum())
print_separator()
# 判断当前字符串是否为"字母"组合, 排列顺序和字母大小写无影响, 不能为空字符串, 不能有除字母外的符号
print("isalpha方法:%s" % "aa".isalpha())
print("isalpha方法:%s" % "Aa".isalpha())
print("isalpha方法:%s" % "Aa#".isalpha())
print("isalpha方法:%s" % "Aa1".isalpha())
print("isalpha方法:%s" % "".isalpha())
print_separator()
# 判断当前字符串中的所有字符均为数字且字符串中至少有一个数字, 不能判断中文数字
print("isdigit方法:%s" % "11".isdigit())
print("isdigit方法:%s" % "11二".isdigit())
print("isdigit方法:%s" % "11a".isdigit())
print("isdigit方法:%s" % "11#".isdigit())
print("isdigit方法:%s" % "".isdigit())
print_separator()
# 判断当前字符串中的所有字符均为数字且字符串中至少有一个数字, 基本和isdigit方法一样, 但是能判断中文数字
print("isnumeric方法:%s" % "11".isnumeric())
print("isnumeric方法:%s" % "11一".isnumeric())
print("isnumeric方法:%s" % "11a".isnumeric())
print("isnumeric方法:%s" % "11#".isnumeric())
print("isnumeric方法:%s" % "".isnumeric())
# 输出:
**************************************************
isalnum方法:True
isalnum方法:True
isalnum方法:True
isalnum方法:False
isalnum方法:False
**************************************************
isalpha方法:True
isalpha方法:True
isalpha方法:False
isalpha方法:False
isalpha方法:False
**************************************************
isdigit方法:True
isdigit方法:False
isdigit方法:False
isdigit方法:False
isdigit方法:False
**************************************************
isnumeric方法:True
isnumeric方法:True
isnumeric方法:False
isnumeric方法:False
isnumeric方法:False
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 判断当前字符串中的所有字符均为十进制且字符串中至少有一个字符
print("isdecimal方法:%s" % "11".isdecimal())
print("isdecimal方法:%s" % "11F".isdecimal())
print("isdecimal方法:%s" % "1.1".isdecimal())
print("isdecimal方法:%s" % "".isdecimal())
# 输出:
isdecimal方法:True
isdecimal方法:False
isdecimal方法:False
isdecimal方法:False
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 判断当前字符串, 如果字符串是有效的Python标识符, 则返回True, 否则返回False, 关键字也返回True
print("isidentifier方法:%s" % "name".isidentifier())
print("isidentifier方法:%s" % "def".isidentifier())
print("isidentifier方法:%s" % "class".isidentifier())
print("isidentifier方法:%s" % "1sss".isidentifier())
print("isidentifier方法:%s" % "name!!".isidentifier())
# 输出:
isidentifier方法:True
isidentifier方法:True
isidentifier方法:True
isidentifier方法:False
isidentifier方法:False
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 字符串大小写反转
print("swapcase方法:%s" % "aBC dE".swapcase())
# 输出:
swapcase方法:Abc De
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 判断当前字符串, 如果字符串是空格字符串, 则返回True, 否则返回False, 且字符串中至少有一个空格
print("isspace方法:%s" % " ".isspace())
print("isspace方法:%s" % "\t ".isspace())
print("isspace方法:%s" % "a".isspace())
print("isspace方法:%s" % "".isspace())
# 输出:
isspace方法:True
isspace方法:True
isspace方法:False
isspace方法:False
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 字符串放在左边, 不够部分使用指定字符进行填充
print("ljust方法:%s" % sentence.ljust(50, "$"))
print_separator()
# 字符串放在右边, 不够部分使用指定字符进行填充
print("rjust方法:%s" % sentence.rjust(50, "$"))
# 输出:
原文:my name is Mason.
**************************************************
ljust方法:my name is Mason.$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
**************************************************
rjust方法:$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$my name is Mason.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
sentence = "my name is Mason."
# maketrans可以做一个映射, 后续可以作用到别的字符串中(不常用)
p = str.maketrans("abcdef", "123456")
print("maketrans方法:%s" % sentence.translate(p))
# 输出:
maketrans方法:my n1m5 is M1son.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 将\t(tab键)延长, 默认延长8, 可以自行指定tabsize, 不常用
print("expandtabs方法:%s" % "a\tb".expandtabs())
print("expandtabs方法:%s" % "a\tb".expandtabs(tabsize=30))
# 输出:
expandtabs方法:a b
expandtabs方法:a b
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
def print_separator(separator="*"):
print(''.center(50, separator))
if __name__ == '__main__':
sentence = "my name is Mason."
print("原文:{sentence}".format(sentence=sentence))
print_separator()
# 字符串指定长度, 长度不够部分使用0填充(不常用)
print("zfill方法:%s" % sentence.zfill(50))
# 输出:
原文:my name is Mason.
**************************************************
zfill方法:000000000000000000000000000000000my name is Mason.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 判断当前字符串是否可以被打印, linux中一切都为文件, tty file, drive file等不能打印, 此时为False, 很少用
print("isprintable方法:%s" % "My Name Is".isprintable())
print("isprintable方法:%s" % "".isprintable())
# 输出:
isprintable方法:True
isprintable方法:True
字典是一种key-value的数据类型
字典的特性:
- dict是无序的
- key必须是唯一的,对于python来说,键(key)必须是可哈希(即可以调用散列函数)的,换句话说就是要可以通过调用散列函数计算出唯一地址的。所以:列表,字典,集合这些可变数据类型都不能作为键(key)来使用。
- 那元组呢?虽然元组是不可变的,但如果元组里面的元素有不可变数据类型时,也不可作为字典中的键(key),即必须对元组做出限制。
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 查询
# 方法1: 通过下标获取值, 在没有键时, 会产生keyError, 不推荐使用
print(info["stu1"])
# 方法2: 使用get方法, 查询时推荐使用此方法, 在没有键时, 会返回None
print(info.get("stu1"))
# 输出:
Tenglan Wu
Tenglan Wu
{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 修改
print("修改前:{dict}".format(dict=info))
info["stu1"] = "武藤兰"
print("修改后:{dict}".format(dict=info))
# 输出:
修改前:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
修改后:{'stu1': '武藤兰', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 增加
print("增加前:{dict}".format(dict=info))
info["stu4"] = "Tom"
print("增加后:{dict}".format(dict=info))
# 输出:
增加前:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
增加后:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya', 'stu4': 'Tom'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 删除
# 方法1: del dict["键"]
print("删除前:{dict}".format(dict=info))
del info["stu1"]
print("删除后:{dict}".format(dict=info))
# 输出:
删除前:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
删除后:{'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 删除
# 方法2: dict.pop("键")
print("删除前:{dict}".format(dict=info))
info.pop("stu1")
print("删除后:{dict}".format(dict=info))
# 输出:
删除前:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
Tenglan Wu
删除后:{'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 删除方法3: dict.popitem(), 默认删除最后一个进入dict的元素, 慎用!!!
print("删除前:{dict}".format(dict=info))
print(info.popitem())
print("删除后:{dict}".format(dict=info))
# 输出:
删除前:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
('stu3', 'Xiaoze Maliya')
删除后:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 判断键/值是否在dict中
print("stu400" in info.keys())
print("stu400" in info.values())
print("stu1" in info.keys())
print("stu1" in info.values())
# 输出:
False
False
True
False
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 使用fromkeys创建dict, 注意: fromkeys创建出来的dict, value都指向同一个内存地址, 只要list中有一个元素变化, 所有的都会受影响
from_keys_dict = dict.fromkeys([1, 2, 3], [1, {"name": "Mason"}])
print(from_keys_dict)
# 修改键1的list中第1个元素值为111, 发现字典中所有value同步修改
from_keys_dict.get(1)[0] = 111
print(from_keys_dict)
# 修改键2的list中第2个元素的value值为Tommy, 发现字典中所有value同步修改
from_keys_dict.get(2)[-1]["name"] = "Tommy"
print(from_keys_dict)
# 输出:
{1: [1, {'name': 'Mason'}], 2: [1, {'name': 'Mason'}], 3: [1, {'name': 'Mason'}]}
{1: [111, {'name': 'Mason'}], 2: [111, {'name': 'Mason'}], 3: [111, {'name': 'Mason'}]}
{1: [111, {'name': 'Tommy'}], 2: [111, {'name': 'Tommy'}], 3: [111, {'name': 'Tommy'}]}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
print("修改前:{dict}".format(dict=info))
# 使用setdefault函数增加dict元素时, 如果dict中已经存在当前设置的key, 则不会覆盖key对应的旧value值
info.setdefault("stu1", "Mark")
print("如果当前设置的key值在dict中, 修改后:{dict}".format(dict=info))
# 使用setdefault函数增加dict元素时, 如果dict中已经不存在当前设置的key, 则会新增当前设置的key:value值到dict中
info.setdefault("stu4", "Mark")
print("如果当前设置的key值不在dict中, 修改后:{dict}".format(dict=info))
# 输出:
修改前:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
如果当前设置的key值在dict中, 修改后:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
如果当前设置的key值不在dict中, 修改后:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya', 'stu4': 'Mark'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
update_dict = {"stu1": "Mason",
"stu4": "Tommy"
}
print("修改前:{dict}".format(dict=info))
# 使用update更新时, 如果新dict中有和老dict中重合key, 则以按照新dict更新, 新dict多出key, 则会在老dict中增加新的key-value
info.update(update_dict)
print("update后:{dict}".format(dict=info))
# 输出:
修改前:{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
update后:{'stu1': 'Mason', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya', 'stu4': 'Tommy'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# dict.items()方法:
print(info)
print(type(info.items()), info.items())
for item in info.items():
print(type(item), item)
# 输出:
{'stu1': 'Tenglan Wu', 'stu2': 'Longze Luola', 'stu3': 'Xiaoze Maliya'}
dict_items([('stu1', 'Tenglan Wu'), ('stu2', 'Longze Luola'), ('stu3', 'Xiaoze Maliya')])
('stu1', 'Tenglan Wu')
('stu2', 'Longze Luola')
('stu3', 'Xiaoze Maliya')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# dict循环
# 方法1: 推荐使用
for key in info.keys():
print(key, info.get(key))
# 方法2:不推荐, info.items会把dict转换成dict_items, 数据量大的时候, 效率低
for key, value in info.items():
print(key, value)
# 输出:
stu1 Tenglan Wu
stu2 Longze Luola
stu3 Xiaoze Maliya
stu1 Tenglan Wu
stu2 Longze Luola
stu3 Xiaoze Maliya
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# dict定义
info = {"stu1": "Tenglan Wu",
"stu2": "Longze Luola",
"stu3": "Xiaoze Maliya"
}
# 下列两种循环方法是等效的
for key in info:
print(key)
for key in info.keys():
print(key)
# 输出:
stu1
stu2
stu3
stu1
stu2
stu3
集合是一个无序的,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
- list或tuple想要转换成set, 必须保证list或者tuple中没有不可哈希的list等元素
使用tuple举例(list同理),例如:
正确示范:
set((1, 2, 3, (4, ))) 会转换为{1, 2, 3, (4,)}
错误示范:
set((1, 2, 3, (4, []))) 会提示转换失败:TypeError: unhashable type: ‘list’
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# list转set
list1 = [1, 2, 3]
list2 = [2, 3, 4, 5]
print(type(list1), list1)
print(type(list2), list2)
# tuple转set
tuple1 = (1, 2, 3)
tuple2 = (2, 3, 4, 5)
print(type(set(tuple1)), set(tuple1))
print(type(set(tuple2)), set(tuple2))
# 输出:
[1, 2, 3]
[2, 3, 4, 5]
{1, 2, 3}
{2, 3, 4, 5}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 集合交集
print(set1.intersection(set2))
print(set1 & set2)
# 输出:
{2, 3}
{2, 3}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 集合并集
print(set1.union(set2))
print(set1 | set2)
# 输出:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 集合差集
print(set1.difference(set2))
print(set1 - set2)
print(set2.difference(set1))
print(set2 - set1)
# 输出:
{1}
{1}
{4, 5}
{4, 5}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 集合对称差集
print(set1.symmetric_difference(set2))
print(set1 ^ set2)
# 输出:
{1, 4, 5}
{1, 4, 5}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 是否为子集/父集
print(set1.issubset(set2))
print(set1.issuperset(set2))
print(set1.issubset({1, 2, 3, 4}))
print(set1.issuperset({1, 2}))
# 输出:
False
False
True
True
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# isdisjoint方法: 如果两个集合没有交集, return True, 否则return False
print(set1.isdisjoint(set2))
print(set1.isdisjoint({4, 5}))
# 输出:
False
True
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 基本操作: add/update
# 单个添加
set1.add("a")
print(set1)
# 输出:
{1, 2, 3, 'a'}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
# 基本操作: remove/pop/discard
# remove: 删除一个set中元素, 如果指定元素不存在于set中, 则会报keyError, remove的元素无法使用变量接收
print("remove前:%s" % set1)
removed_elem = set1.remove(1)
print("remove的元素是否可以通过变量接收:%s, remove后:%s" % (removed_elem, set1))
# 输出:
remove前:{1, 2, 3}
remove的元素是否可以通过变量接收:None, remove后:{2, 3}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
# 基本操作: remove/pop/discard
# pop: 随机删除一个set中元素, 不能指定需要删除的元素, pop的元素可以使用变量接收
print("pop前:%s" % set1)
poped_elem = set1.pop()
print("pop的元素是否可以通过变量接收:%s, pop后:%s" % (poped_elem, set1))
# 输出:
pop前:{1, 2, 3}
pop的元素是否可以通过变量接收:1, pop后:{2, 3}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
# 基本操作: remove/pop/discard
# discard: 删除一个set中元素, 如果指定元素不存在于set中, 则不会影响原set, discard的元素无法使用变量接收
print("discard前:%s" % set1)
discarded_elem = set1.discard(1)
print("discard的元素是否可以通过变量接收:%s, discard后:%s" % (discarded_elem, set1))
# 输出:
discard前:{1, 2, 3}
discard的元素是否可以通过变量接收:None, discard后:{2, 3}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
# clear方法:
print("clear前:%s" % set1)
set1.clear()
print("clear后:%s" % set1)
# 输出:
clear前:{1, 2, 3}
clear后:set()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
# copy方法:
print("copy前:%s, id:%s" % (set1, id(set1)))
copy_set = set1.copy()
print("copy后:%s, id:%s" % (copy_set, id(copy_set)))
# 输出:
copy前:{1, 2, 3}, id:2204157401120
copy后:{1, 2, 3}, id:2204163840032
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 使用交集刷新set1
set1.intersection_update(set2)
print(set1)
# 输出:
{2, 3}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 使用并集刷新set1
set1.update(set2)
print(set1)
# 输出:
{1, 2, 3, 4, 5}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 使用差集刷新set1
set1.difference_update(set2)
print(set1)
# 输出:
{1}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
if __name__ == '__main__':
# 集合定义
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
# 使用对称差集刷新set1
set1.symmetric_difference_update(set2)
print(set1)
# 输出:
{1, 4, 5}