AI实战训练营Python打卡——第五天

AI实战训练营Python打卡——第五天,第1张

AI实战训练营Python打卡——第五天
字符串

print(r'C:Program FilesIntelWifiHelp')  
# C:Program FilesIntelWifiHelp
C:Program FilesIntelWifiHelp
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( t )。
也可以使用换行符 [ n ]。
"""
print(para_str)
# 这是一个多行字符串的实例
# 多行字符串可以使用制表符
# TAB (    )。
# 也可以使用换行符 [
#  ]。
​
para_str = '''这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( t )。
也可以使用换行符 [ n ]。
'''
print(para_str)
# 这是一个多行字符串的实例
# 多行字符串可以使用制表符
# TAB (      )。
# 也可以使用换行符 [ 
#  ]。
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( 	 )。
也可以使用换行符 [ 
 ]。

这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( 	 )。
也可以使用换行符 [ 
 ]。

str1 = 'I Love LsgoGroup'
print(str1[:6])  # I Love
print(str1[5])  # e
print(str1[:6] + " 插入的字符串 " + str1[6:])  
# I Love 插入的字符串  LsgoGroup
​
s = 'Python'
print(s)  # Python
print(s[2:4])  # th
print(s[-5:-2])  # yth
print(s[2])  # t
print(s[-1])  # n
I Love
e
I Love 插入的字符串  LsgoGroup
Python
th
yth
t
n
'''
capitalize() 将字符串的第一个字符转换为大写。
lower() 转换字符串中所有大写字符为小写。
upper() 转换字符串中的小写字母为大写。
swapcase() 将字符串中大写转换为小写,小写转换为大写。
'''
str2 = 'xiaoxie'
print(str2.capitalize())  # Xiaoxie
str2 = "DAXIExiaoxie"
print(str2.lower())  # daxiexiaoxie
print(str2.upper())  # DAXIEXIAOXIE
print(str2.swapcase())  # daxieXIAOXIE
Xiaoxie
daxiexiaoxie
DAXIEXIAOXIE
daxieXIAOXIE
str2 = "DAXIExiaoxie"
print(str2.count('xi'))  # 2
2
str2 = "DAXIExiaoxie"
print(str2.endswith('ie'))  # True
print(str2.endswith('xi'))  # False
print(str2.startswith('Da'))  # False
print(str2.startswith('DA'))  # True
True
False
False
True
str2 = "DAXIExiaoxie"
print(str2.find('xi'))  # 5
print(str2.find('ix'))  # -1
print(str2.rfind('xi'))  # 9
5
-1
9
# isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False。
str3 = '12345'
print(str3.isnumeric())  # True
str3 += 'a'
print(str3.isnumeric())  # False
True
False
str4 = '1101'
print(str4.ljust(8, '0'))  # 11010000
print(str4.rjust(8, '0'))  # 00001101
11010000
00001101
'''
lstrip([chars]) 截掉字符串左边的空格或指定字符。
rstrip([chars]) 删除字符串末尾的空格或指定字符。
strip([chars]) 在字符串上执行lstrip()和rstrip()。
'''
str5 = ' I Love LsgoGroup '
print(str5.lstrip())  # 'I Love LsgoGroup '
print(str5.lstrip().strip('I'))  # ' Love LsgoGroup '
print(str5.rstrip())  # ' I Love LsgoGroup'
print(str5.strip())  # 'I Love LsgoGroup'
print(str5.strip().strip('p'))  # 'I Love LsgoGrou'
I Love LsgoGroup 
 Love LsgoGroup 
 I Love LsgoGroup
I Love LsgoGroup
I Love LsgoGrou
# replace(old, new [, max]) 把 将字符串中的old替换成new,如果max指定,则替换不超过max次。
str5 = ' I Love LsgoGroup '
print(str5.strip().replace('I', 'We'))  # We Love LsgoGroup
We Love LsgoGroup
u = "www.baidu.com.cn"
# 使用默认分隔符
print(u.split())  # ['www.baidu.com.cn']
​
# 以"."为分隔符
print((u.split('.')))  # ['www', 'baidu', 'com', 'cn']
​
# 分割0次
print((u.split(".", 0)))  # ['www.baidu.com.cn']
​
# 分割一次
print((u.split(".", 1)))  # ['www', 'baidu.com.cn']
​
# 分割两次
print(u.split(".", 2))  # ['www', 'baidu', 'com.cn']
​
# 分割两次,并取序列为1的项
print((u.split(".", 2)[1]))  # baidu
​
# 分割两次,并把分割后的三个部分保存到三个变量
u1, u2, u3 = u.split(".", 2)
print(u1)  # www
print(u2)  # baidu
print(u3)  # com.cn
['www.baidu.com.cn']
['www', 'baidu', 'com', 'cn']
['www.baidu.com.cn']
['www', 'baidu.com.cn']
['www', 'baidu', 'com.cn']
baidu
www
baidu
com.cn
c = '''say
hello
baby'''
​
print(c)
# say
# hello
# baby
​
print(c.split('n'))  # ['say', 'hello', 'baby']
say
hello
baby
['say', 'hello', 'baby']
string = "hello boy<[www.baidu.com]>byebye"
print(string.split('[')[1].split(']')[0])  # www.baidu.com
print(string.split('[')[1].split(']')[0].split('.'))  # ['www', 'baidu', 'com']
www.baidu.com
['www', 'baidu', 'com']
# splitlines([keepends]) 按照行('r', 'rn', n')分隔,返回一个包含各行作为元素的列表,如果参数keepends为 False,不包含换行符,如果为 True,则保留换行符。
str6 = 'I n Love n LsgoGroup'
print(str6.splitlines())  # ['I ', ' Love ', ' LsgoGroup']
print(str6.splitlines(True))  # ['I n', ' Love n', ' LsgoGroup']
['I ', ' Love ', ' LsgoGroup']
['I n', ' Love n', ' LsgoGroup']
str7 = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str7.maketrans(intab, outtab)
print(trantab)  # {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str7.translate(trantab))  # th3s 3s str3ng 2x1mpl2....w4w!!!
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
th3s 3s str3ng 2x1mpl2....w4w!!!
'''
maketrans(intab, outtab) 创建字符映射的转换表,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
translate(table, deletechars="") 根据参数table给出的表,转换字符串的字符,要过滤掉的字符放到deletechars参数中。
'''
str7 = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str7.maketrans(intab, outtab)
print(trantab)  # {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str7.translate(trantab))  # th3s 3s str3ng 2x1mpl2....w4w!!!
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
th3s 3s str3ng 2x1mpl2....w4w!!!
str8 = "{0} Love {1}".format('I', 'Lsgogroup')  # 位置参数
print(str8)  # I Love Lsgogroup
​
str8 = "{a} Love {b}".format(a='I', b='Lsgogroup')  # 关键字参数
print(str8)  # I Love Lsgogroup
​
str8 = "{0} Love {b}".format('I', b='Lsgogroup')  # 位置参数要在关键字参数之前
print(str8)  # I Love Lsgogroup
​
str8 = '{0:.2f}{1}'.format(27.658, 'GB')  # 保留小数点后两位
print(str8)  # 27.66GB
I Love Lsgogroup
I Love Lsgogroup
I Love Lsgogroup
27.66GB
print('%c' % 97)  # a
print('%c %c %c' % (97, 98, 99))  # a b c
print('%d + %d = %d' % (4, 5, 9))  # 4 + 5 = 9
print("我叫 %s 今年 %d 岁!" % ('小明', 10))  # 我叫 小明 今年 10 岁!
print('%o' % 10)  # 12
print('%x' % 10)  # a
print('%X' % 10)  # A
print('%f' % 27.658)  # 27.658000
print('%e' % 27.658)  # 2.765800e+01
print('%E' % 27.658)  # 2.765800E+01
print('%g' % 27.658)  # 27.658
text = "I am %d years old." % 22
print("I said: %s." % text)  # I said: I am 22 years old..
print("I said: %r." % text)  # I said: 'I am 22 years old.'
a
a b c
4 + 5 = 9
我叫 小明 今年 10 岁!
12
a
A
27.658000
2.765800e+01
2.765800E+01
27.658
I said: I am 22 years old..
I said: 'I am 22 years old.'.
字典

# 用 hash(X),只要不报错,证明 X 可被哈希,即不可变,反过来不可被哈希,即可变。
print(hash('Name'))  # 7047218704141848153
​
print(hash((1, 2, 'Python')))  # 1704535747474881831
​
print(hash([1, 2, 'Python']))
# TypeError: unhashable type: 'list'
​
1242838551751862538
-6389152729907118152
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:UsersJINBIN~1AppDataLocalTemp/ipykernel_11984/2347817978.py in 
      4 print(hash((1, 2, 'Python')))  # 1704535747474881831
      5 
----> 6 print(hash([1, 2, 'Python']))
      7 # TypeError: unhashable type: 'list'

TypeError: unhashable type: 'list'

print(hash({1, 2, 3}))
# TypeError: unhashable type: 'set'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:UsersJINBIN~1AppDataLocalTemp/ipykernel_11984/773250044.py in 
----> 1 print(hash({1, 2, 3}))
      2 # TypeError: unhashable type: 'set'

TypeError: unhashable type: 'set'

'''
数值、字符和元组 都能被哈希,因此它们是不可变类型。
列表、集合、字典不能被哈希,因此它是可变类型。
'''
'n数值、字符和元组 都能被哈希,因此它们是不可变类型。n列表、集合、字典不能被哈希,因此它是可变类型。n'
dic1 = {1: 'one', 2: 'two', 3: 'three'}
print(dic1)  # {1: 'one', 2: 'two', 3: 'three'}
print(dic1[1])  # one
print(dic1[4])  # KeyError: 4
{1: 'one', 2: 'two', 3: 'three'}
one
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:UsersJINBIN~1AppDataLocalTemp/ipykernel_11984/3707680317.py in 
      2 print(dic1)  # {1: 'one', 2: 'two', 3: 'three'}
      3 print(dic1[1])  # one
----> 4 print(dic1[4])  # KeyError: 4

KeyError: 4

dic2 = {'rice': 35, 'wheat': 101, 'corn': 67}
print(dic2)  # {'wheat': 101, 'corn': 67, 'rice': 35}
print(dic2['rice'])  # 35
{'rice': 35, 'wheat': 101, 'corn': 67}
35
dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
​
print(dic)
# {'a': 1, 'b': 2, 'c': 3}
​
dic['a'] = 11
print(dic)
# {'a': 11, 'b': 2, 'c': 3}
​
dic['d'] = 4
print(dic)
# {'a': 11, 'b': 2, 'c': 3, 'd': 4}
{'a': 1, 'b': 2, 'c': 3}
{'a': 11, 'b': 2, 'c': 3}
{'a': 11, 'b': 2, 'c': 3, 'd': 4}
dic1 = dict([('apple', 4139), ('peach', 4127), ('cherry', 4098)])
print(dic1)  # {'cherry': 4098, 'apple': 4139, 'peach': 4127}
​
dic2 = dict((('apple', 4139), ('peach', 4127), ('cherry', 4098)))
print(dic2)  # {'peach': 4127, 'cherry': 4098, 'apple': 4139}
{'apple': 4139, 'peach': 4127, 'cherry': 4098}
{'apple': 4139, 'peach': 4127, 'cherry': 4098}
# 这种情况下,键只能为字符串类型,并且创建的时候字符串不能加引号,加上就会直接报语法错误。
dic = dict(name='Tom', age=10)
print(dic)  # {'name': 'Tom', 'age': 10}
print(type(dic))  # 
{'name': 'Tom', 'age': 10}

dic = {'Name': 'lsgogroup', 'Age': 7}
print(dic.keys())  # dict_keys(['Name', 'Age'])
lst = list(dic.keys())  # 转换为列表
print(lst)  # ['Name', 'Age']
dict_keys(['Name', 'Age'])
['Name', 'Age']
dic = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
print(dic.values())
# dict_values(['female', 7, 'Zara'])
​
print(list(dic.values()))
# [7, 'female', 'Zara']
​
dict_values(['female', 7, 'Zara'])
['female', 7, 'Zara']
dic = {'Name': 'Lsgogroup', 'Age': 7}
print(dic.items())
# dict_items([('Name', 'Lsgogroup'), ('Age', 7)])
​
print(tuple(dic.items()))
# (('Name', 'Lsgogroup'), ('Age', 7))
​
print(list(dic.items()))
# [('Name', 'Lsgogroup'), ('Age', 7)]
dict_items([('Name', 'Lsgogroup'), ('Age', 7)])
(('Name', 'Lsgogroup'), ('Age', 7))
[('Name', 'Lsgogroup'), ('Age', 7)]
dic = {'Name': 'Lsgogroup', 'Age': 27}
print("Age 值为 : %s" % dic.get('Age'))  # Age 值为 : 27
print("Sex 值为 : %s" % dic.get('Sex', "NA"))  # Sex 值为 : NA
print(dic)  # {'Name': 'Lsgogroup', 'Age': 27}
Age 值为 : 27
Sex 值为 : NA
{'Name': 'Lsgogroup', 'Age': 27}
dic = {'Name': 'Lsgogroup', 'Age': 7}
print("Age 键的值为 : %s" % dic.setdefault('Age', None))  # Age 键的值为 : 7
print("Sex 键的值为 : %s" % dic.setdefault('Sex', None))  # Sex 键的值为 : None
print(dic)  
# {'Age': 7, 'Name': 'Lsgogroup', 'Sex': None}
Age 键的值为 : 7
Sex 键的值为 : None
{'Name': 'Lsgogroup', 'Age': 7, 'Sex': None}
dic = {'Name': 'Lsgogroup', 'Age': 7}
​
# in 检测键 Age 是否存在
if 'Age' in dic:
    print("键 Age 存在")
else:
    print("键 Age 不存在")
​
# 检测键 Sex 是否存在
if 'Sex' in dic:
    print("键 Sex 存在")
else:
    print("键 Sex 不存在")
​
# not in 检测键 Age 是否存在
if 'Age' not in dic:
    print("键 Age 不存在")
else:
    print("键 Age 存在")
键 Age 存在
键 Sex 不存在
键 Age 存在
dic1 = {1: "a", 2: [1, 2]}
print(dic1.pop(1), dic1)  # a {2: [1, 2]}
​
# 设置默认值,必须添加,否则报错
print(dic1.pop(3, "nokey"), dic1)  # nokey {2: [1, 2]}
​
del dic1[2]
print(dic1)  # {}
a {2: [1, 2]}
nokey {2: [1, 2]}
{}
# dict.popitem()删除并返回字典中的最后一对键和值,如果字典已经为空,却调用了此方法,就报出KeyError异常。
dic1 = {1: "a", 2: [1, 2], 3: 'ss', 4: 'yy'}
print(dic1.popitem())  # {2: [1, 2]}
print(dic1)  # (1, 'a')
(4, 'yy')
{1: 'a', 2: [1, 2], 3: 'ss'}
dic = {'Name': 'Zara', 'Age': 7}
print("字典长度 : %d" % len(dic))  # 字典长度 : 2
dic.clear()
print("字典删除后长度 : %d" % len(dic))  
# 字典删除后长度 : 0
字典长度 : 2
字典删除后长度 : 0
# dict.copy()返回一个字典的浅复制
dic1 = {'Name': 'Lsgogroup', 'Age': 7, 'Class': 'First'}
dic2 = dic1.copy()
print(dic2)  
# {'Age': 7, 'Name': 'Lsgogroup', 'Class': 'First'}
{'Name': 'Lsgogroup', 'Age': 7, 'Class': 'First'}
dic1 = {'user': 'lsgogroup', 'num': [1, 2, 3]}
​
# 引用对象
dic2 = dic1  
# 浅拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
dic3 = dic1.copy()  
​
print(id(dic1))  # 148635574728
print(id(dic2))  # 148635574728
print(id(dic3))  # 148635574344
​
# 修改 data 数据
dic1['user'] = 'root'
dic1['num'].remove(1)
​
# 输出结果
print(dic1)  # {'user': 'root', 'num': [2, 3]}
print(dic2)  # {'user': 'root', 'num': [2, 3]}
print(dic3)  # {'user': 'runoob', 'num': [2, 3]}
2285649866368
2285649866368
2285649866432
{'user': 'root', 'num': [2, 3]}
{'user': 'root', 'num': [2, 3]}
{'user': 'lsgogroup', 'num': [2, 3]}
dic = {'Name': 'Lsgogroup', 'Age': 7}
dic2 = {'Sex': 'female', 'Age': 8}
dic.update(dic2)
print(dic)  
# {'Sex': 'female', 'Age': 8, 'Name': 'Lsgogroup'}
{'Name': 'Lsgogroup', 'Age': 8, 'Sex': 'female'}
集合

basket = set()
basket.add('banana')
print(basket)
# add方法一次只能加一个
{'banana'}
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)  # {'banana', 'apple', 'pear', 'orange'}
# 会自动去掉重复的元素
{'orange', 'pear', 'banana', 'apple'}
# 
a = set('abracadabra')
print(a)  
# {'r', 'b', 'd', 'c', 'a'}
​
b = set(("Google", "Lsgogroup", "Taobao", "Taobao"))
print(b)  
# {'Taobao', 'Lsgogroup', 'Google'}
​
c = set(["Google", "Lsgogroup", "Taobao", "Google"])
print(c)  
# {'Taobao', 'Lsgogroup', 'Google'}
# 使用set(value)工厂函数,把列表或元组转换成集合。
{'d', 'c', 'b', 'a', 'r'}
{'Lsgogroup', 'Google', 'Taobao'}
{'Lsgogroup', 'Google', 'Taobao'}
lst = [0, 1, 2, 3, 4, 5, 5, 3, 1]
print(set(lst))
# 在将元组或列表转化为集合时,会自动删除重复的元素
{0, 1, 2, 3, 4, 5}
s = set(['Google', 'Baidu', 'Taobao'])
print(len(s))  # 3
3
s = set(['Google', 'Baidu', 'Taobao'])
for item in s:
    print(item)
    
Baidu
Google
Taobao
s = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in s)  # True
print('Facebook' not in s)  # True
True
True
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)  
# {'orange', 'cherry', 'banana', 'apple'}
​
fruits.add("apple")
print(fruits)  
# {'orange', 'cherry', 'banana', 'apple'}
{'orange', 'cherry', 'banana', 'apple'}
{'orange', 'cherry', 'banana', 'apple'}
x = {"apple", "banana", "cherry"}
y = {"google", "baidu", "apple"}
x.update(y)
print(x)
# {'cherry', 'banana', 'apple', 'google', 'baidu'}
​
y.update(["lsgo", "dreamtech"])
print(y)
# {'lsgo', 'baidu', 'dreamtech', 'apple', 'google'}
{'google', 'cherry', 'banana', 'apple', 'baidu'}
{'google', 'lsgo', 'dreamtech', 'apple', 'baidu'}
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)  # {'apple', 'cherry'}
{'cherry', 'apple'}
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)  # {'apple', 'cherry'}
# set.discard(value) 用于移除指定的集合元素。remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。
{'cherry', 'apple'}
fruits = {"apple", "banana", "cherry"}
x = fruits.pop()
print(fruits)  # {'cherry', 'apple'}
print(x)  # banana
# 移出最后一个
{'banana', 'apple'}
cherry
'''
set.intersection(set1, set2) 返回两个集合的交集。
set1 & set2 返回两个集合的交集。
set.intersection_update(set1, set2) 交集,在原始的集合上移除不重叠的元素。
'''
a = set('abracadabra')
b = set('alacazam')
print(a)  # {'r', 'a', 'c', 'b', 'd'}
print(b)  # {'c', 'a', 'l', 'm', 'z'}
​
c = a.intersection(b)
print(c)  # {'a', 'c'}
print(a & b)  # {'c', 'a'}
print(a)  # {'a', 'r', 'c', 'b', 'd'}
​
a.intersection_update(b)
print(a)  # {'a', 'c'}
{'d', 'c', 'b', 'a', 'r'}
{'c', 'l', 'z', 'm', 'a'}
{'c', 'a'}
{'c', 'a'}
{'d', 'c', 'b', 'a', 'r'}
{'c', 'a'}
'''
set.union(set1, set2) 返回两个集合的并集。
set1 | set2 返回两个集合的并集。
'''
a = set('abracadabra')
b = set('alacazam')
print(a)  # {'r', 'a', 'c', 'b', 'd'}
print(b)  # {'c', 'a', 'l', 'm', 'z'}
​
print(a | b)  
# {'l', 'd', 'm', 'b', 'a', 'r', 'z', 'c'}
​
c = a.union(b)
print(c)  
# {'c', 'a', 'd', 'm', 'r', 'b', 'z', 'l'}
{'d', 'c', 'b', 'a', 'r'}
{'c', 'l', 'z', 'm', 'a'}
{'d', 'c', 'l', 'b', 'z', 'm', 'a', 'r'}
{'d', 'c', 'l', 'b', 'z', 'm', 'a', 'r'}
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)  # True
print(x <= y)  # True
​
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b"}
z = x.issubset(y)
print(z)  # False
print(x <= y)  # False
# set.issubset(set)判断集合是不是被其他集合包含,如果是则返回 True,否则返回 False。
# set1 <= set2 判断集合是不是被其他集合包含,如果是则返回 True,否则返回 False。
​
True
True
False
False
'''
set.issuperset(set)用于判断集合是不是包含其他集合,如果是则返回 True,否则返回 False。
set1 >= set2 判断集合是不是包含其他集合,如果是则返回 True,否则返回 False。
'''
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)  # True
print(x >= y)  # True
​
x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)  # False
print(x >= y)  # False
True
True
False
False
# set.isdisjoint(set) 用于判断两个集合是不是不相交,如果是返回 True,否则返回 False。
x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
z = x.isdisjoint(y)
print(z)
False
se = set(range(4))
li = list(se)
tu = tuple(se)
​
print(se, type(se))  # {0, 1, 2, 3} 
print(li, type(li))  # [0, 1, 2, 3] 
print(tu, type(tu))  # (0, 1, 2, 3) 
{0, 1, 2, 3} 
[0, 1, 2, 3] 
(0, 1, 2, 3) 
'''
Python 提供了不能改变元素的集合的实现版本,即不能增加或删除元素,类型名叫frozenset。需要注意的是frozenset仍然可以进行集合 *** 作,只是不能用带有update的方法。
​
frozenset([iterable]) 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
'''
x = frozenset('abcdefg')
print(x)
frozenset({'d', 'c', 'b', 'e', 'g', 'f', 'a'})
序列

'''
在 Python 中,序列类型包括字符串、列表、元组、集合和字典,这些序列支持一些通用的 *** 作,
但比较特殊的是,集合和字典不支持索引、切片、相加和相乘 *** 作。
'''
'n在 Python 中,序列类型包括字符串、列表、元组、集合和字典,这些序列支持一些通用的 *** 作,n但比较特殊的是,集合和字典不支持索引、切片、相加和相乘 *** 作。n'
# list(sub) 把一个可迭代对象转换为列表
a = list()
print(a)  # []
​
b = 'I Love LsgoGroup'
b = list(b)
print(b)  
# ['I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p']
​
c = (1, 1, 2, 3, 5, 8)
c = list(c)
print(c)  # [1, 1, 2, 3, 5, 8]
[]
['I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p']
[1, 1, 2, 3, 5, 8]
# tuple(sub) 把一个可迭代对象转换为元组。
a = tuple()
print(a)  # ()
​
b = 'I Love LsgoGroup'
b = tuple(b)
print(b)  
# ('I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p')
​
c = [1, 1, 2, 3, 5, 8]
c = tuple(c)
print(c)  # (1, 1, 2, 3, 5, 8)
()
('I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p')
(1, 1, 2, 3, 5, 8)
# str(obj) 把obj对象转换为字符串
a = 123
b = str(a)
print(b, type(b))
123 
# len(s) 返回对象(字符、列表、元组等)长度或元素个数。
a = list()
print(len(a))  # 0
​
b = ('I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p')
print(len(b))  # 16
​
c = 'I Love LsgoGroup'
print(len(c))  # 16
0
16
16
# max(sub)返回序列或者参数集合中的最大值
print(max(1, 2, 3, 4, 5))  # 5
print(max([-8, 99, 3, 7, 83]))  # 99
print(max('IloveLsgoGroup'))  # v
5
99
v
# min(sub)返回序列或参数集合中的最小值
print(min(1, 2, 3, 4, 5))  # 1
print(min([-8, 99, 3, 7, 83]))  # -8
print(min('IloveLsgoGroup'))  # G
1
-8
G
与可选参数的和
# sum(iterable[, start=0]) 返回序列iterable与可选参数start的总和。
print(sum([1, 3, 5, 7, 9]))  # 25
print(sum([1, 3, 5, 7, 9], 10))  # 35
print(sum((1, 3, 5, 7, 9)))  # 25
print(sum((1, 3, 5, 7, 9), 20))  # 45
# 输出序列与可选参数的和
25
35
25
45
'''
sorted(iterable, key=None, reverse=False) 对所有可迭代的对象进行排序 *** 作。
iterable -- 可迭代对象。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
返回重新排序的列表。
'''
x = [-8, 99, 3, 7, 83]
print(sorted(x))  # [-8, 3, 7, 83, 99]
print(sorted(x, reverse=True))  # [99, 83, 7, 3, -8]
​
t = ({"age": 20, "name": "a"}, {"age": 25, "name": "b"}, {"age": 10, "name": "c"})
x = sorted(t, key=lambda a: a["age"])
print(x)
# [{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
[-8, 3, 7, 83, 99]
[99, 83, 7, 3, -8]
[{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
x = sorted(t, key=lambda a: a['age'])
print(x)
[{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
'''
reversed(seq) 函数返回一个反转的迭代器。
seq -- 要转换的序列,可以是 tuple, string, list 或 range。
'''
s = 'lsgogroup'
x = reversed(s)
print(type(x))  # 
print(x)  # 
print(list(x))
# ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']
​
t = ('l', 's', 'g', 'o', 'g', 'r', 'o', 'u', 'p')
print(list(reversed(t)))
# ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']
​
r = range(5, 9)
print(list(reversed(r)))
# [8, 7, 6, 5]
​
x = [-8, 99, 3, 7, 83]
print(list(reversed(x)))
# [83, 7, 3, 99, -8]


['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']
['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']
[8, 7, 6, 5]
[83, 7, 3, 99, -8]
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
a = list(enumerate(seasons))
print(a)  
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
​
b = list(enumerate(seasons, 1))
print(b)  
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
​
for i, element in a:
    print('{0},{1}'.format(i, element))
# 0,Spring
# 1,Summer
# 2,Fall
# 3,Winter
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
0,Spring
1,Summer
2,Fall
3,Winter
'''
zip(iter1 [,iter2 [...]])
用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
我们可以使用 list() 转换来输出列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号 *** 作符,可以将元组解压为列表。
'''
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
​
zipped = zip(a, b)
print(zipped)  # 
print(list(zipped))  # [(1, 4), (2, 5), (3, 6)]
zipped = zip(a, c)
print(list(zipped))  # [(1, 4), (2, 5), (3, 6)]
​
a1, a2 = zip(*zip(a, b))
print(list(a1))  # [1, 2, 3]
print(list(a2))  # [4, 5, 6]

[(1, 4), (2, 5), (3, 6)]
[(1, 4), (2, 5), (3, 6)]
[1, 2, 3]
[4, 5, 6]

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5690071.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存