Python(三)

元组(tuple)

元组的相关链接:tuple

  • 顺序存储相同/不同类型的元素
  • 元组定义,使用将元素括起来,元素之间用“,”,隔开

实例1:

1
db_info = ("192.168.10.1",3306,"root","root123")
  • 特性:不可变,不支持添加、修改、删除元素操作

实例2:

1
2
3
4
#这里会报错,元素是不能修改的
db_info[0] = 5

del db_info[1]#不支持删除

结果:

1
2
3
4
5
6
7
8
9
10
11
12
TypeError                                 Traceback (most recent call last)
<ipython-input-2-006550c675f2> in <module>()
----> 1 db_info[0] = 5

TypeError: 'tuple' object does not support item assignment
-----------------------------------------------------------------------

TypeError Traceback (most recent call last)
<ipython-input-7-3bc97da19d51> in <module>()
----> 1 del db_info[1]#不支持删除

TypeError: 'tuple' object doesn't support item deletion
  • 查询:通过下标查询元组指定位置的元素

实例3:

1
2
3
4
ip = db_info[0]
port = db_info[1]
print(ip)
print(port)

结果:

1
2
192.168.10.1
3306
  • 空元组、只有一个元素的元组

实例4:

1
2
3
4
5
6
7
#定义只有一个元素的元组
one_tuple = ("zhangsan",)

#空元组
none_tuple = ()
print(one_tuple)
print(none_tuple)

结果:

1
2
('zhangsan',)
()
  • 循环遍历元组

实例5:

1
2
3
#循环遍历元组
for item in db_info:
print(item)

结果:

1
2
3
4
192.168.10.1
3306
root
root123

字典(dict)

字典相关链接:dict

  • 存储Key-Value键值对类型的数据
  • 字典定义:{key1:value1 , key2:value2 , ···}

实例6:

1
2
#字典
user_info_dict = {"name":"悟空","age":100,"gender":"male","job":"取经"}
  • 查询:根据Key查找Value
  • 字典具有添加、修改、删除操作

实例7:

1
2
3
4
5
#对键值进行修改以及取值
user_info_dict = {"name":"悟空","age":100,"gender":"male","job":"取经"}
user_info_dict["job"] = "取经|偷桃"
print(user_info_dict)
print("%s的年龄是:%d,性别:%s,工作内容:%s"%(user_info_dict["name"],user_info_dict["age"],user_info_dict["gender"],user_info_dict["job"]))

结果:

1
2
{'name': '悟空', 'age': 100, 'gender': 'male', 'job': '取经|偷桃'}
悟空的年龄是:100,性别:male,工作内容:取经|偷桃

实例8:

1
2
3
#key不能相同,会默认后面的键值
user_info_dict = {"name":"悟空","age":100,"gender":"male","job":"取经","job":"偷桃"}
print(user_info_dict)

结果:

1
{'name': '悟空', 'age': 100, 'gender': 'male', 'job': '偷桃'}

实例9:

1
2
3
#添加键值对
user_info_dict["tel"] = "13812345567"
print(user_info_dict)

结果:

1
{'name': '悟空', 'age': 100, 'gender': 'male', 'job': '偷桃', 'tel': '13812345567'}
  • 字典的内置方法

  1. dict.get(key, default=None)

定义: Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

1
2
3
4
5
1. 参数
1. key -- 字典中要查找的键。
2. default -- 如果指定键的值不存在时,返回该默认值值。
2. 返回值:
返回指定键的值,如果值不在字典中返回默认值None

实例10:

1
2
3
4
dict = {'Name': 'Runoob', 'Age': 27}

print ("Age 值为 : %s" % dict.get('Age'))
print ("Sex 值为 : %s" % dict.get('Sex', "NA"))

结果:

1
2
Age 值为 : 27
Sex 值为 : NA
  1. dict.keys()

定义:Python 字典(Dictionary) keys() 函数以列表返回一个字典所有的键。

1
2
3
4
1. 参数
NA
2. 返回值:
返回一个字典所有的键

实例11:

1
2
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.keys())

结果:

1
Value : ['Name', 'Age']
  1. dict.values()

定义:Python 字典(Dictionary) values() 函数以列表返回字典中的所有值。

1
2
3
4
1. 参数
NA
2. 返回值
返回字典中所有值

实例12:

1
2
3
dict = {'Name': 'Zara', 'Age': 7}

print ("Value : %s" % dict.values())

结果:

1
Value : ['Zara', 7]
  1. dict.items()

    定义:Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

1
2
3
4
1. 参数
NA
2. 返回值
返回可遍历的(键,值)元组数组

实例13:

1
2
3
4
5
6
7
dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}

print ("字典值 : %s" % dict.items())

# 遍历字典列表
for key,values in dict.items():
print (key,values)

结果:

1
2
3
4
字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
  1. dict.clear()

定义:Python 字典(Dictionary) clear() 函数用于删除字典内所有元素。

1
2
3
4
1. 参数
NA
2. 返回值
该函数没有任何返回值

实例14:

1
2
3
4
5
dict = {'Name': 'Zara', 'Age': 7};

print ("Start Len : %d" % len(dict))
dict.clear()
print ("End Len : %d" % len(dict))

结果:

1
2
Start Len : 2
End Len : 0

集合Set

  • 无序存储不同数据类型,不重复元素的序列

实例15:

1
2
3
4
5
6
#集合对列表去重
student_list = ["zhansan","lisi","wangwu",'zhangsan','lisi']
student_set = set(student_list)
print(type(student_set))
print(len(student_set))
print(student_set)

结果:

1
2
3
<class 'set'>
4
{'zhansan', 'zhangsan', 'wangwu', 'lisi'}
  • 创建空集合

实例16:

1
2
3
#创建一个空集合
none_dict = {}#注意这是创建一个空字典
none_set = set() #空集合

结果:

1
2
{}
set()
  • 通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果:

实例17:

1
2
3
4
#add添加元素到集合
name_set = {"zhansan","lisi"}
name_set.add("wangwu")
print(name_set)

结果:

1
{'zhansan', 'wangwu', 'lisi'}
  • 使用update(序列)方法将一个序列中的元素添加到集合中,同时对元素去重

实例18:

1
2
3
#update(序列)
name_set.update(["悟空","八戒"],["张飞","李逵"])
print(name_set)

结果:

1
{'悟空', '李逵', 'wangwu', 'zhansan', '八戒', '张飞', 'lisi'}
  • remove() 和 discard() 以及pop()的区别,都是删除的指令

实例19:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
name_set.update(["悟空","八戒"],["张飞","李逵"])
print(name_set)

#remove 删除元素
name_set.remove("悟空")
print(name_set)

#dicard(元素),删除一个不存在的元素,不会报错
name_set.discard("西游记")

#pop()随机删除集合中的某个元素,并返回被删除的元素
print(name_set)
name = name_set.pop()
print(name_set)
# print(name)

#使用remove删除一个不存在的元素,会报错
name_set.remove("西游记")

结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{'悟空', '李逵', 'wangwu', 'zhansan', '八戒', '张飞', 'lisi'}
{'李逵', 'wangwu', 'zhansan', '八戒', '张飞', 'lisi'}
{'李逵', 'wangwu', 'zhansan', '八戒', '张飞', 'lisi'}
{'wangwu', 'zhansan', '八戒', '张飞', 'lisi'}
wangwu
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-31-c5efead19a78> in <module>()
13
14 #使用remove删除一个不存在的元素,会报错
---> 15 name_set.remove("西游记")
16
17

KeyError: '西游记'

集合操作

  1. 交集intersection(&)
  2. 并集union(|)
  3. 差集difference(-)
  4. 对称差集symmetric_difference(^)

实例20:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#交集
num_set1 = {1,2,4,7}
num_set2 = {2,5,8,9}
inter_set1 = num_set1 & num_set2
inter_set2 = num_set1.intersection(num_set2)
print(inter_set1)
print(inter_set2)

#并集
union_set1 = num_set1 | num_set2
union_set2 = num_set1.union(num_set2)
print(union_set1)
print(union_set2)

#差集(set1中除去并集所剩下的集合)
diff_set1 = num_set1 - num_set2
diff_set2 = num_set1.difference(num_set2)
print(diff_set1)
print(diff_set2)

#对称差集(set1和set2分别除去交集后再并集)
sym_diff_set1 = num_set1 ^ num_set2
sym_diff_set2 = num_set1.symmetric_difference(num_set2)
print(sym_diff_set1)
print(sym_diff_set2)

结果:

1
2
3
4
5
6
7
8
{2}
{2}
{1, 2, 4, 5, 7, 8, 9}
{1, 2, 4, 5, 7, 8, 9}
{1, 4, 7}
{1, 4, 7}
{1, 4, 5, 7, 8, 9}
{1, 4, 5, 7, 8, 9}

字符串常用内置方法

字符串相关链接:字符串

  1. str.find(str, beg=0, end=len(string))

    定义:Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

1
2
3
4
5
6
1.参数:
str -- 指定检索的字符串
beg -- 开始索引,默认为0
end -- 结束索引,默认为字符串的长度。
2.返回值
如果包含子字符串返回开始的索引值,否则返回-1

实例21:

1
2
3
4
5
6
7
8
9
10
11
#find
line = "hello world hello python"

#hello第一次出现的脚标
print(line.find("hello"))

#指定查找的起始脚标
print(line.find("hello",6))

#不存在的子字符串返回-1
print(line.find("java"))

结果:

1
2
3
0
12
-1
  1. str.count(sub, start= 0,end=len(string))

    定义:Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

1
2
3
4
5
6
1.参数:
sub -- 搜索的子字符串
start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0
end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
2.返回值
该方法返回子字符串在字符串中出现的次数。

实例22:

1
2
3
4
5
6
str = "this is string example....wow!!!"

sub = "i"
print ("str.count(sub, 4, 40) : ", str.count(sub, 4, 40))
sub = "wow"
print ("str.count(sub) : ", str.count(sub))

结果:

1
2
str.count(sub, 4, 40) :  2
str.count(sub) : 1
  1. str.replace(old, new[, max])

定义:Python replace() 方法把字符串中的old(旧字符串) 替换成new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

1
2
3
4
5
6
1.参数:
old -- 将被替换的子字符串。
new -- 新字符串,用于替换old子字符串。
max -- 可选字符串, 替换不超过 max 次
2.返回值
返回字符串中的old(旧字符串)替换成new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过max 次。

实例23:

1
2
3
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))

结果:

1
2
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
  1. str.split(str=””, num=string.count(str))

定义:Python split()通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num 个子字符串

1
2
3
4
5
1.参数:
str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num -- 分割次数。
2.返回值
返回分割后的字符串列表。

实例24:

1
2
3
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print (str.split( ))
print (str.split(' ', 1 ))

结果:

1
2
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
  1. startswith

    定义:Python startswith()方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

1
2
3
4
5
6
1.参数:
str -- 检测的字符串。
strbeg -- 可选参数用于设置字符串检测的起始位置。
strend -- 可选参数用于设置字符串检测的结束位置。
2.返回值
如果检测到字符串则返回True,否则返回False

实例25:

1
2
3
4
str = "this is string example....wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'is', 2, 4 ))
print (str.startswith( 'this', 2, 4 ))

结果:

1
2
3
True
True
False
  1. str.endswith(suffix[, start[, end]])

定义:Python endswith()方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数”start”与”end”为检索字符串的开始与结束位置。

1
2
3
4
5
6
1.参数:
suffix -- 该参数可以是一个字符串或者是一个元素。
start -- 字符串中的开始位置。
end -- 字符中结束位置。
2.返回值
如果字符串含有指定的后缀返回True,否则返回False

实例26:

1
2
3
4
5
6
7
8
9
str = "this is string example....wow!!!"

suffix = "wow!!!"
print (str.endswith(suffix))
print (str.endswith(suffix,20))

suffix = "is"
print (str.endswith(suffix, 2, 4))
print (str.endswith(suffix, 2, 6))

结果:

1
2
3
4
True
True
True
False

startswith、endswith的应用场景

1
2
3
4
5
#需要找出2018年以log结尾的文件
files = ["20171201.txt","20171201.log","20180101.txt","20180101.log"]
for file in files:
if file.startswith("2018") and file.endswith("log"):
print("2018年待处理日志:%s"%file)

结果:

1
2018年待处理日志:20180101.log
  1. str.upper()

定义:Python upper()方法将字符串中的小写字母转为大写字母。

1
2
3
4
1.参数:
NA
2.返回值
返回小写字母转为大写字母的字符串。

实例27:

1
2
3
str = "this is string example....wow!!!"

print ("str.upper() : ", str.upper())

结果:

1
str.upper() :  THIS IS STRING EXAMPLE....WOW!!!
  1. str.lower()

    定义:Python lower()方法转换字符串中所有大写字符为小写。

1
2
3
4
1.参数:
NA
2.返回值
返回大写字母转为小写字母的字符串。

实例28:

1
2
3
str = "THIS IS STRING EXAMPLE....WOW!!!"

print (str.lower())

结果:

1
this is string example....wow!!!

-------------本文结束感谢您的阅读-------------


本文标题:Python(三)

文章作者:HuXuzhe

发布时间:2018年07月08日 - 10:07

最后更新:2018年07月08日 - 10:07

原始链接:https://huxuzhe.github.io/2018/07/08/Python-三/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

HuXuzhe wechat
关注微信公众号:"AI数据分析算法",轻轻扫一扫,加入我们的AI_LEGENDS !
坚持原创,您的支持将鼓励我继续创作!
0%