Python快速而美丽[v1.0.0][常用技巧]

时间:2020-8-1 作者:admin


拼接字符串的7种方法

占位符:来自C语言的

>>> print("%s %s %s" % ("Hello","Python","World"))
Hello Python World

占位符除了%s以外还有%d %f %x分别代表一个整数、一个浮点数、一个十六进制数

format函数拼接

>>> str = 'Hello {}! My name is {}.'.format('Python World', 'davieyang')
>>> print(str)
Hello Python World! My name is davieyang.

异常

此处需要注意的是,大括号里不能有空格,否则会报异常

>>> str1 = 'Hello { }! My name is { }.'.format('Python World', 'davieyang')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: ' '

format函数参数形式

>>> str = 'Hello {1}! My name is {0}.'.format('Python World', 'davieyang')
>>> print(str)
Hello davieyang! My name is Python World.

>>> str = 'Hello {name}! My name is {name_name}.'.format(name='Python World', name_name='davieyang')
>>> print(str)
Hello Python World! My name is davieyang.

元组方式

>>> tuple = ('Hello', '', 'World')
>>> print(tuple)
('Hello', '', 'World')
>>> tuple = ('Hello', ' ', 'World')
>>> print(tuple)
('Hello', ' ', 'World')
>>> like_tuple = ('Hello' ' ' 'World')
>>> print(like_tuple)
Hello World
>>> like_tuple = ('Hello' ' ' 'World' ' ' '1')
>>> print(like_tuple)
Hello World 1
>>> like_tuple = ('Hello' ' ' 'World' ' ' 1)
  File "<stdin>", line 1
    like_tuple = ('Hello' ' ' 'World' ' ' 1)

这种方式要求必须都是字符串,不能混用数据类型

模板拼接

>>> from string import Template
>>> str = Template('${str1} ${str2}')
>>> print(str.safe_substitute(str1 = "Hello", str2 = "world"))
Hello world

常用+方式

>>> str1 = "Hello"
>>> str2 = "World"
>>> print(str1 + str2)
HelloWorld

join方法

>>> str_list = ['Hello', 'World']
>>> str_join1 = ' '.join(str_list)
>>> str_join2 = '_'.join(str_list)
>>> print(str_join1)
Hello World
>>> print(str_join2)
Hello_World

>>> str_tuple = ('Hello', 'World')
>>> str_join1 = ' '.join(str_list)
>>> str_join2 = '_'.join(str_list)
>>> print(str_join1)
Hello World
>>> print(str_join2)
Hello_World

f-string方式

>>> name = "world"
>>> another_name = "davieyang"
>>> str = f"Hello {name}. My name is {another_name}."
>>> print(str)
Hello world. My name is davieyang.

【列表推导】【字典推导】【集合推导】

推导是从一个数据序列构建一个新的数据序列的过程

>>> some_list = [1,2,3,4,5]
>>> another_list = [x+1 for x in some_list]
>>> another_list
[2, 3, 4, 5, 6]

>>> numbers = [1,2,3,4,5,6,7,8]
>>> even = [number for number in numbers if number%2 ==0]
>>> even
[2, 4, 6, 8]

>>> some_list = [1,2,3,4,5,2,6,4,1,4,5,8,7,9,0,1,2]
>>> even_set = {x for x in some_list if x%2 == 0}
>>> even_set
{0, 2, 4, 6, 8}

>>> d = {x : x%2==0 for x in range(1,11)}
>>> d
{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

>>> teams = ["aaa", "bbb", "ccc", "ddd"]
>>> print({key:value for value, key in enumerate(teams)})
{'aaa': 0, 'bbb': 1, 'ccc': 2, 'ddd': 3}

三元操作符

[表达式为真的返回值] if [表达式] else [表达式为假的返回值]

>>> y=10
>>> x =10 if (y==9) else 20
>>> x
20
>>> y=9
>>> x =10 if (y==9) else 20
>>> x
10

>>> class A:
...     def __init__(self, param1, param2):
...             self.para = param1
...             self.param = param2
...             print(self.para + self.param)
...
>>> class B:
...     def __init__(self, param1, param2):
...             self.para = param1
...             self.param = param2
...             print(self.param+self.para)
...
>>> y=1
>>> x = (A if y==1 else B)("string1", "string2")
string1string2
>>> y=2
>>> x = (A if y==1 else B)("string1", "string2")
string2string1

>>> def small(a,b,c):
...     return a if a <=b and a<=c else(b if b<=a and b<=c else c)
...
>>> small(1,0,1)
0
>>> small(1,2,2)
1
>>> small(2,2,3)
2
>>> small(5,4,3)
3

>>> list1 = [m**2 if m > 10 else m**4 for m in range(50)]
>>> list1
[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

同时迭代两个列表

>>> list1 = ["Davieyang", "Davieyang.D.Y"]
>>> list2 = ["Ethan", "Alex"]
>>> for one, two in zip(list1, list2):
...     print(one + " vs " + two)
...
Davieyang vs Ethan
Davieyang.D.Y vs Alex

>>> list1 = [1,2,3]
>>> list2 = ["davieyang", "Davieyang", "Davieyang.D.Y"]
>>> print(dict(zip(list1, list2)))
{1: 'davieyang', 2: 'Davieyang', 3: 'Davieyang.D.Y'}

带索引的列表迭代

>>> teams = ["davieyang","Davieyang","Davieyang.D.Y","davieyang.cool"]
>>> for index, teammember in enumerate(teams):
...     print(index, teammember)
...
0 davieyang
1 Davieyang
2 Davieyang.D.Y
3 davieyang.cool

迭代列表组合

>>> from itertools import combinations
>>> list1 = ["a", "b", "c", "d", "e", "f"]
>>> for new in combinations(list1, 3):
...     print(new)
...
('a', 'b', 'c')
('a', 'b', 'd')
('a', 'b', 'e')
('a', 'b', 'f')
('a', 'c', 'd')
('a', 'c', 'e')
('a', 'c', 'f')
('a', 'd', 'e')
('a', 'd', 'f')
('a', 'e', 'f')
('b', 'c', 'd')
('b', 'c', 'e')
('b', 'c', 'f')
('b', 'd', 'e')
('b', 'd', 'f')
('b', 'e', 'f')
('c', 'd', 'e')
('c', 'd', 'f')
('c', 'e', 'f')
('d', 'e', 'f')

>>> from itertools import permutations
>>> list2 = [1,2,3,4,5,6]
>>> for new in permutations(list2, 4):
...     print(new)
...
(1, 2, 3, 4)
(1, 2, 3, 5)
(1, 2, 3, 6)
(1, 2, 4, 3)
(1, 2, 4, 5)
(1, 2, 4, 6)
(1, 2, 5, 3)
(1, 2, 5, 4)
(1, 2, 5, 6)
(1, 2, 6, 3)
...
>>> for new in permutations(list1, 3):
...     print(new)
...
('a', 'b', 'c')
('a', 'b', 'd')
('a', 'b', 'e')
('a', 'b', 'f')
...

combinations的重点在组合,而permutations的重点在排列

统计元素出现次数

>>> from collections import Counter
>>> c = Counter("Hello World")
>>> c
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})

查找出现频率最高的两个元素

>>> c.most_common(2)
[('l', 3), ('o', 2)]

统计列表中出现次数最多的元素

>>> from collections import Counter
>>> numbers = [1,2,3,4,54,5,6,3,2,3,4,45,2,2,3,34,4,45,5,65,2,2,34,4,5]
>>> print(Counter(numbers).most_common()[0][0])
2
>>> print(max(set(numbers), key=numbers.count))
2

集合并集/交集/差集

集合Set是一个无序不重复的元素集合

并集set(list1)|set(list2)

>>> list1 = [1,2,3,4,5]
>>> list2 = [2,3,7,8,9]
>>> print(set(list1)|set(list2))
{1, 2, 3, 4, 5, 7, 8, 9}
>>> print(set(list1).union(set(list2)))
{1, 2, 3, 4, 5, 7, 8, 9}

交集set(list1)&set(list2)

>>> list1 = [1,2,3,4,5]
>>> list2 = [2,3,7,8,9]
>>> print(set(list1)&set(list2))
{2, 3}
>>> print(set(list1).intersection(set(list2)))
{2, 3}
>>>

差集set(list1)-set(list2)

>>> list1 = [1,2,3,4,5]
>>> list2 = [2,3,7,8,9]
>>> print(set(list1)-set(list2))
{1, 4, 5}
>>> print(set(list1).difference(set(list2)))
{1, 4, 5}
>>>

对称差集set(list1)^set(list2)

>>> list1 = [1,2,3,4,5]
>>> list2 = [2,3,7,8,9]
>>> print(set(list1)^set(list2))
{1, 4, 5, 7, 8, 9}
>>> print(set(list1).symmetric_difference(set(list2)))
{1, 4, 5, 7, 8, 9}

列表去重

用集合去重

>>> list1 = [11,22,33,33,44,55,55,66]
>>> set1 = set(list1)
>>> set1
{33, 66, 11, 44, 22, 55}
>>> list1 = list(set1)
>>> list1
[33, 66, 11, 44, 22, 55]

用字典去重

>>> list1 = [11,22,33,33,44,55,55,66]
>>> list1 = {}.fromkeys(list1).keys()
>>> list1
dict_keys([11, 22, 33, 44, 55, 66])

用列表推导

>>> list1 = [11,22,33,33,44,55,55,66]
>>> list2 = []
>>> list3 = [list2.append(i) for i in list1 if i not in list2]
>>> list2
[11, 22, 33, 44, 55, 66]

用字典并保持原顺序输出

>>> list1 = [11,22,33,33,44,55,55,66]
>>> list2 = list(set(list1))
>>> list2.sort(key=list1.index)
>>> list2
[11, 22, 33, 44, 55, 66]
声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。