Python初级方法
1. 多赋值
2. 交换元素的值
| a = "我是a的值"
b = "我是b的值"
a,b = b,a
|
3. 元素自操作
| a = 5
a +=1 #自加1
a -=1 #自减1
a /=2 #自除2
a *=2 #自乘2
a ## =2 #自己的2次方
print(a)
|
4. 使用三元操作符赋值
下面的语句是说“如果 y 是 9,给 x 赋值 10,不然赋值为 20”
| x = 10 if (y == 9) else 20
|
同样地,我们可以对类做这种操作:
| x = (classA if y == 1 else classB)(param1, param2)
|
在上面的例子里 classA 与 classB 是两个类,其中一个类的构造函数会被调用。
我们甚至可以在列表推导中使用三元运算符:
| [ m## 2 if m ; 10 else m## 4 for m in range(20) ]
|
5. 字符串反转
使用 Python 中 slicing 操作,来实现字符串反转:
| my_string = "ABCDE"
reversed_string = my_string[::-1]
print(reversed_string)
|
6. 首字母大写
使用的是 String 类的title()方法:
| my_string = "my name is chaitanya baweja"
# using the title() function of string class
new_string = my_string.title()
print(new_string)
|
7. 取组成字符串的元素
使用 set 中只能存储不重复的元素这一特性:
| my_string = "aavvccccddddeee"
# converting the string to a set
temp_set = set(my_string)
# stitching set into a string using join
new_string = ''.join(temp_set)
print(new_string)
|
12. 回文检测
| my_string = "abcba"
if my_string == my_string[::-1]:
print("palindrome")
else:
print("not palindrome")
|
13. 元素重复次数
在Python中,有很多方法可以做这件事情,但是我最喜欢的还是 Counter 这个类。Counter会计算每一个元素出现的次数,Counter()会返回一个字典,元素作为key,出现的次数作为 value。我们也可以使用 most_common() 这个方法来获取出现字数最多的元素。
| from collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']
count = Counter(my_list) # defining a counter object
print(count) # Of all elements
# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
print(count['b']) # of individual element
# 3
print(count.most_common(1)) # most frequent element
|
14. 变位词使用
Counter的一个很有意思的用法是找变位词:变位词一种把某个词或句子的字母的位置(顺序)加以改换所形成的新词。使用 Counter 得到的两个对象如果相等,则他们是变位词:
| from collections import Counter
str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:
print('1 and 2 anagram')
if cnt_1 == cnt_3:
print('1 and 3 anagram')
|
16. 枚举遍历
遍历列表中的值和对应的索引:
| my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):
print('{0}: {1}'.format(index, value))
|
17. 对象使用内存大小
| import sys
num = 21
print(sys.getsizeof(num))
|
18. 合并两个字典
在 Python 2 中,使用 update() 方法来合并,在 Python 3.5 中,更加简单,在下面的代码片段中,合并了两个字典,在两个字典存在交集的时候,则使用后一个进行覆盖。
使用 **,函数将参数以字典的形式导入
| dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict)
|
20. 列表展开
有时候,你不知道你当前列表的嵌套深度,但是你希望把他们展开,放到一维的列表中。实现如下:
| from iteration_utilities import deepflatten
# if you only have one depth nested_list, use this
def flatten(l):
return [item for sublist in l for item in sublist]
l = [[1,2,3],[3]]
print(flatten(l)) # 只有一个深度的列表
# [1, 2, 3, 3]
# if you don't know how deep the list is nested
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
# 不知道列表嵌套的深度
print(list(deepflatten(l, depth=3)))
|
Numpy flatten 可以更好的处理你格式化好的数据。
21. 随机取样
下面的例子中,使用 random 库,实现了从列表中随机取样。
| import random
my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2
samples = random.sample(my_list,num_samples)
print(samples)
|
随机取样,我推荐使用 secrets 库来实现,更安全。下面的代码片段只能在 Python3 中运行:
| import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
my_list = ['a','b','c','d','e']
num_samples = 2
samples = secure_random.sample(my_list, num_samples)
print(samples)
|
22. 生成式
| a = 'qwertyuiop'
c = {k:v for k,v in enumerate(a)}
>>> c = {0: 'q', 1: 'w', 2: 'e', 3: 'r', 4: 't', 5: 'y', 6: 'u', 7: 'i', 8: 'o', 9: 'p'}
c = "abcdefg"
a = [x for x in c]
>>> a = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
|