|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
Lambda #运算优先级最低逻辑运算符: or逻辑运算符: and逻辑运算符:not成员测试: in, not in同一性测试: is, is not比较: <,<=,>,>=,!=,==按位或: |按位异或: ^按位与: &移位: << ,>>加法与减法: + ,-乘法、除法与取余: *, / ,%正负号: +x,-x |
#交换变量值
a,b = 5,10 print(a,b) #5 10 a,b = b,a print(a,b) #10 5
#将列表中的所有元素组合成字符串
a = ['Python','is','awesome'] print(' '.join(a)) #Python is awesome
#查找列表中频率最高的值
a = [1,2,3,1,2,3,2,2,4,5,1] print(max(set(a),key = a.count)) #2
#检查两个字符串是不是由相同字母不同顺序组成
from collections import Counter str1 = '1234abcd' str2 = '1243abcd' print(Counter(str1) == Counter(str2)) #True
#反转字符串
a = 'abcdefghijklmnopqrstuvwxyz' print(a[::-1]) #zyxwvutsrqponmlkjihgfedcba for char in reversed(a): print(char,end='') #zyxwvutsrqponmlkjihgfedcba num = 123456789 print(int(str(num)[::-1])) #987654321
#反转列表
a = [5,4,3,2,1] print(a[::-1]) #[1, 2, 3, 4, 5] for ele in reversed(a): print(ele,end='') #12345
#转置二维数组
original = [['a','b'],['c','d'],['e','f']] transposed = zip(*original) print(list(transposed)) #[('a', 'c', 'e'), ('b', 'd', 'f')]
#链式比较
b = 6 print(4 < b < 7) #True print(1 == b < 20) #False
#链式函数调用
def product(a,b): return a * b def add(a,b): return a + b b = True print((product if b else add)(5,7)) #35 b = False print((product if b else add)(5,7)) #12
#字典 get 方法
d = {'a':1,'b':2}
print(d.get('c',3)) #3
#For Else
a = [1,2,3,4,5] for el in a: if el == 0: break else: print('did not break out of for loop')
#转换列表为逗号分割符格式
items = ['foo','bar','xyz'] print(','.join(items)) #foo,bar,xyz numbers = [2,3,5,10] print((','.join(map(str,numbers)))) #2,3,5,10 data = [2,'hello',3,3.4] print(','.join(map(str,data))) #2,hello,3,3.4
#合并字典
d1 = {'a':1}
d2 = {'b':2}
print({**d1,**d2}) #{'a': 1, 'b': 2}
print(dict(d1.items() | d2.items())) #{'b': 2, 'a': 1}
d1.update(d2)
print(d1) #{'a': 1, 'b': 2}
#列表中最小和最大值的索引
lst = [40,10,20,30] def minIndex(lst): return min(range(len(lst)),key=lst.__getitem__) def maxIndex(lst): return max(range(len(lst)),key=lst.__getitem__) print(minIndex(lst)) #1 print(maxIndex(lst)) #0
#移除列表中的重复元素
items = [2,2,3,3,1] newitmes2 = list(set(items)) print(newitmes2) #[1, 2, 3] from collections import OrderedDict items = ['foo','bar','bar','foo'] print(list(OrderedDict.fromkeys(items).keys())) #['foo', 'bar']
浙公网安备 33010602011771号