python
1、交换变量
a,b = 1,2
a,b = b,a
2、 Counter : 判断两个字符串是否是anagram
anagram,就是两个词所用的字母及其个数都是一样的,但是它们字母的位置不一样
from collections import Counter
Counter(str1) == Counter(str2)
补充: Counter:计数时使用Counter计数对象
from collections import Counter
c = Counter('abcdeabcdabcaba') # count elements from a string
# Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
c.most_common(3) # three most common elements
# [('a', 5), ('b', 4), ('c', 3)]
sorted(c) # list all unique elements,sorted+dict,根据keys对dict排序,输出dict的keys值
# ['a', 'b', 'c', 'd', 'e']
sorted(c.elements()) # list elements with repetitions
# ['a',ount of letter 'a'
# 5 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
''.join(sorted(c.elements())) # 转为字符串形式
'aaaaabbbbcccdde'
sum(c.values()) # total of all counts
# 15
c['a'] # c
3-1、复制list
在python中使用b=a来复制list是错的。在Python中,这样的写法b和a指向的是同一块内存,对b操作,就相当于对a操作。所以正确的写法有以下几种:
方法一:b=a[:]。
方法二:b=list(a)。
方法三:使用Python 3的copy()函数,直接复制list,类似a[:]
3-2、查找list中出现次数最多的元素
a=[1,2,3,2,3,4,3]
print(max(set(a),key=a.count))
3-3、 list中的最小和最大索引
list = [7,2,3,3,5]
print(max(range(len(list)),key=list.__getitem__))
print(min(range(len(list)),key=list.__getitem__))
4、字符串、数字、list倒转
#字符串
str1 = "asdf"
print(str1[::-1])
#数字
num= 1234
print(str(num)[::-1])
#list
list1 = [1,2,3]
print(list1[::-1])
5、iterable转化为str
S.join(iterable) -> str
# 将list中的所有元素转为单个字符串
a =["a","bc","d"]
print(" ".join(a))
# 输出为 a bc d
#字符串数字混合list
list = [1,"b","c"]
print(",".join(map(str,list)))
6、链式调用
x=1
y=2 if x==1 else 3
list=[i for i in range(2)]
np.where(condition=,x=,y=)
#两者等价
x if condition else y
def multiply(a,b):
return a*b
def add(a,b):
return a+b
bool = True
print((add if bool else multiply)(1,2))
8、合并字典
dict1={"a":12}
dict2={"b":13}
dict1.update(dict2)
9、查找字典
data = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
# 查找字典,存在输出values
is_admin1 = data.get('Michael', False)
# 95
# 不存在输出False
is_admin2 = data.get('John', False)
# False
10、查找所有组合
和collections库一样,还有一个库叫itertools,对某些问题真能高效地解决。其中一个用例是查找所有组合,他能告诉你在一个组中元素的所有不能的组合方式
from itertools import combinations
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
print(game)
# ('Packers', '49ers')
# ('Packers', 'Ravens')
# ('Packers', 'Patriots')
# ('49ers', 'Ravens')
# ('49ers', 'Patriots')
# ('Ravens', 'Patriots')
combinations(range(4), 3)
#(0,1,2), (0,1,3), (0,2,3), (1,2,3)
11、查找所有排列
import itertools
friends = ['Monique', 'Ashish', 'Devon', 'Bernie']
print(list(itertools.permutations(friends, r=2)))
numpy
1、numpy高维操作理解
2、numpy/tensor筛选
x = np.arange(5)
print(x) #[0 1 2 3 4]
print(x<3) #[ True True True False False]
print(x[x<3]) #[0 1 2]
sess=tf.Session()
print(sess.run(tf.boolean_mask(x,x<3))) #[0 1 2]
3、更改numpy的形状
a=np.arange(6).reshape([2,3])
a.ravel() # 可以使数组变成一维数组
4、tensor -> numpy
numpy = tensor.eval(session=tf.Session())