交换变量值
"""pythonic way of value swapping"""
a,b=5,10
print(a,b)
#解法一:
a,b=b,a
print(a,b)
#解法二:
c=a
a=b
b=c
print(a,c)
将列表中的所有元素组合成字符串
list1=["Python","is","awesome"]
print(" ".join(list1))
查找列表中频率最高的值
"""most frequent element in a list"""
list1=[1,2,3,1,5,6,5,1,2,2,2,2]
print(max(list1,key=list1.count))
"""using Counter from collections"""
from collections import Counter
cnt=Counter(list1)
print(cnt) #Counter({2: 5, 1: 3, 5: 2, 3: 1, 6: 1})
print(cnt.most_common(2)) #[(2, 5), (1, 3)]
检查两个字符串是不是由相同字母不同顺序组成
str1='abc'
str2='cba'
from collections import Counter
print(Counter(str1)==Counter(str2))
反转字符串
"""reversing string with special case of slice step param"""
str1="abcdefg"
print(str1[::-1])
"""iterating over string contents in reverse efficiently"""
print(reversed(str1)) #<reversed object at 0x000001B1E3C6A6D8>
for char in reversed(str1):
print(char)
"""reversing an integer through type conversion and slicing"""
num=123456789
print(int(str(num)[::-1])) #987654321
反转列表
"""reversing list with special case of slice step param"""
list1=[1,2,3,4]
print(list1[::-1])
"""iterating over list contents in reverse efficiently"""
for ele in reversed(list1):
print(ele)
转置二维数组
"""transpose 2d array [[a,b],[c,d],[e,f]] --> [[a,c,e],[b,d,f]]"""
original=[["a","b"],["c","d"],["e","f"]]
transposed=zip(*original)
# print(tuple(transposed)) #(('a', 'c', 'e'), ('b', 'd', 'f'))
print(list(transposed)) #[('a', 'c', 'e'), ('b', 'd', 'f')]
链式比较
"""chained comparison with all kind of operators"""
b=5
print(2<b<9) #True
print(1==b<10) #False 等价于 1==b and b<10
链式函数调用
"""calling different functions with same arguments based on condition"""
def product(a,b):
return a*b
def add(a,b):
return a+b
c=True
print((product if c else add)(2,4))
复制列表
"""a fast way to make a shallow copy of a list"""
a=[1,2,3]
b=a
b[0]=10
print(a) #[10, 2, 3]
print(b) #[10, 2, 3]
print(id(a)==id(b)) #True
# 使用切片后内存地址改变
b=a[:]
b[0]=10
print(a) #[1, 2, 3]
print(b) #[10, 2, 3]
print(id(a)==id(b)) #Fals
"""copy list by typecasting moethod"""
b=list(a)
print(id(a)==id(b)) #False
"""using the list.copy() method (python3 only)"""
b=a.copy()
print(a is b) #False
"""copy nested lists using copy.deepcopy"""
import copy
list1=[1,2,[1,2]]
list2=list1.copy()
list3=copy.deepcopy(list1)
list1[2][0]=10
list1[0]=100
print(list1) #[100, 2, [10, 2]]
print(list2) #[1, 2, [10, 2]]
print(list3) #[1, 2, [1, 2]]
字典 get 方法
"""returning None or default value when key is not in dict"""
dict1={"a":1,"b":2}
print(dict1.get("a",10))
通过「键」排序字典元素
"""Sort a dictionary by its values with the built-in sorted() function and a 'key' argument"""
dict1={"a":10,"b":2,"c":3,}
print(sorted(dict1.items(),key=lambda x:x[1]))
"""sort using operator.itemgetter as the sort key instead of a lambda"""
from operator import itemgetter
print(sorted(dict1.items(),key=itemgetter(1)))
"""sort dict keys by value"""
print(sorted(dict1,key=dict1.get))
For Else
"""else gets called when for loop does not reach break statement"""
a=[1,2,3]
for i in a:
if i==0:
break
else:
print("did not break out of for loop")
转换列表为逗号分割符格式
"""converts list to comma separated satring"""
item=["I","like","Python"]
print(",".join(item))
"""list of numbers to comma separated"""
numbers=[1,2,3,4,5]
print(",".join(map(str,numbers)))
"""list of mix data"""
data=[2,"hello",2,5]
print(",".join(map(str,data)))
合并字典
d1={"a":1}
d2={"b":2}
print({**d1,**d2})
print(dict(d1.items() | d2.items()))
d1.update(d2)
print(d1)
列表中最小和最大值的索引
"""find index of Min/Max element"""
list1=[2,5,7]
def minIndex(list):
return min(range(len(list)),key=list.__getitem__)
def maxIndex(list):
return max(range(len(list)),key=list.__getitem__)
print(minIndex(list1))
print(maxIndex(list1))
移除列表中的重复元素
"""remove duplicate items from list ,note: does not preserve the original list order"""
item=[1,1,2,3,4,4,5]
#解法一
print(list(set(item)))
#解法二:
li=list()
for i in item:
if i not in li:
li.append(i)
print(li)
#解法三:
from collections import OrderedDict
print(list(OrderedDict.fromkeys(item).keys()))