Python 必知的 20 个骚操做!

如下为译文:python

Python 是一个解释型语言,可读性与易用性让它愈来愈热门。git

正如 Python 之禅中所述:安全

优美胜于丑陋,明了胜于晦涩。app

在你的平常编码中,如下技巧能够给你带来意想不到的收获。dom

 


 

 

字符串反转this

 

下面的代码片断,使用 Python 中 slicing 操做,来实现字符串反转:编码

 

1# Reversing a string using slicing
2
3my_string = "ABCDE"
4reversed_string = my_string[::-1]
5
6print(reversed_string)
7
8# Output
9# EDCBAspa

在这篇文章(https://medium.com/swlh/how-to-reverse-a-string-in-python-66fc4bbc7379)中,你能够了解更多细节。3d

 

首字母大写code

 

下面的代码片断,能够将字符串进行首字母大写,使用的是 String 类的 title() 方法:

 

1my_string = "my name is chaitanya baweja"
2
3# using the title() function of string class
4new_string = my_string.title()
5
6print(new_string)
7
8# Output
9# My Name Is Chaitanya Baweja

 

取组成字符串的元素

 

下面的代码片断,能够用来找出一个字符串中全部组成他的元素,咱们使用的是 set 中只能存储不重复的元素 这一特性:

 

1my_string = "aavvccccddddeee"
2
3# converting the string to a set
4temp_set = set(my_string)
5
6# stitching set into a string using join
7new_string = ''.join(temp_set)
8
9print(new_string)
10
11# Output
12# acedv

 

 

重复输出String/List

 

能够对 String/List 进行乘法运算,这个方法,可使用它们任意倍增。

 

1n = 3 # number of repetitions
2my_string = "abcd"
3my_list = [1,2,3]
4
5print(my_string*n)
6# abcdabcdabcd
7
8print(my_string*n)
9# [1,2,3,1,2,3,1,2,3]

有一个颇有意思的用法,定义包含n个常量的列表:

 

1n = 4
2my_list = [0]*n # n 表示所需列表的长度
3# [0, 0, 0, 0]

 

列表推导式

 

列表推导式提供了一种更优雅的方式处理列表。

如下代码片断中,将旧列表中的元素乘以2来建立新的列表:

 

1original_list = [1,2,3,4]
2
3new_list = [2*x for x in original_list]
4
5print(new_list)
6# [2,4,6,8]

 

交换两个变量值

 

Python 交换两个变量的值不须要建立一个中间变量,很简单就能够实现:

 

1a = 1
2b = 2
3
4a, b = b, a
5
6print(a) # 2
7print(b) # 1

 

字符串拆分

 

使用 split() 方法能够将一个字符串拆分红多个子串,你也能够将分割符做为参数传递进行,进行分割。

 

1string_1 = "My name is Chaitanya Baweja"
2string_2 = "sample/ string 2"
3
4# default separator ' '
5print(string_1.split())
6# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
7
8# defining separator as '/'
9print(string_2.split('/'))
10# ['sample', ' string 2']

 

转存失败从新上传取消

字符串拼接

 

join()方法能够将字符串列表组合成一个字符串,下面的代码片断中,我使用,将全部的字符串拼接到一块儿:

 

1list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
2
3# Using join with the comma separator
4print(','.join(list_of_strings))
5
6# Output
7# My,name,is,Chaitanya,Baweja

 

回文检测

 

在前面,咱们已经说过了,如何翻转一个字符串,因此回文检测很是的简单:

 

1my_string = "abcba"
2
3if my_string == my_string[::-1]:
4    print("palindrome")
5else:
6    print("not palindrome")
7
8# Output
9# palindrome

 

元素重复次数

 

在Python中,有不少方法能够作这件事情,可是我最喜欢的仍是 Counter 这个类。

Counter会计算每个元素出现的次数,Counter()会返回一个字典,元素做为key,出现的次数做为 value。

咱们也可使用 most_common() 这个方法来获取出现字数最多的元素。

 

1from collections import Counter
2
3my_list = ['a','a','b','b','b','c','d','d','d','d','d']
4count = Counter(my_list) # defining a counter object
5
6print(count) # Of all elements
7# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
8
9print(count['b']) # of individual element
10# 3
11
12print(count.most_common(1)) # most frequent element
13# [('d', 5)]

 

变位词

 

使用Counter的一个颇有意思的用法是找变位词:

变位词一种把某个词或句子的字母的位置(顺序)加以改换所造成的新词。

使用 Counter 获得的两个对象若是相等,则他们是变位词:

 

1from collections import Counter
2
3str_1, str_2, str_3 = "acbde", "abced", "abcda"
4cnt_1, cnt_2, cnt_3  = Counter(str_1), Counter(str_2), Counter(str_3)
5
6if cnt_1 == cnt_2:
7    print('1 and 2 anagram')
8if cnt_1 == cnt_3:
9    print('1 and 3 anagram')

 

try-except-else

 

 

在Python中,使用 try-except 进行异常捕获。else 可用于当没有异常发生时执行。

若是你须要执行一些代码,无论是否发生过异常,请使用 final:

 

1a, b = 1,0
2
3try:
4    print(a/b)
5    # exception raised when b is 0
6except ZeroDivisionError:
7    print("division by zero")
8else:
9    print("no exceptions raised")
10finally:
11    print("Run this always")

 

枚举遍历

 

下面的代码片断中,遍历列表中的值和对应的索引:

 

1my_list = ['a', 'b', 'c', 'd', 'e']
2
3for index, value in enumerate(my_list):
4    print('{0}: {1}'.format(index, value))
5
6# 0: a
7# 1: b
8# 2: c
9# 3: d
10# 4: e

 

 

对象使用内存大小

 

下面的代码片断展现了,如何获取一个对象所占用的内存大小:

 

1import sys
2
3num = 21
4
5print(sys.getsizeof(num))
6
7# In Python 2, 24
8# In Python 3, 28

 

合并两个字典

 

在 Python 2 中,使用 update() 方法来合并,在 Python 3.5 中,更加简单,在下面的代码片断中,合并了两个字典,在两个字典存在交集的时候,则使用后一个进行覆盖。

 

1dict_1 = {'apple': 9, 'banana': 6}
2dict_2 = {'banana': 4, 'orange': 8}
3
4combined_dict = {**dict_1, **dict_2}
5
6print(combined_dict)
7# Output
8# {'apple': 9, 'banana': 4, 'orange': 8}

 

代码执行时间

 

下面的代码片断中,使用了 time 这个库,来计算代码执行的时间:

 

1import time
2
3start_time = time.time()
4# Code to check follows
5a, b = 1,2
6c = a+ b
7# Code to check ends
8end_time = time.time()
9time_taken_in_micro = (end_time- start_time)*(10**6)
10
11print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)

 

列表展开

 

有时候,你不知道你当前列表的嵌套深度,可是你但愿把他们展开,放到一维的列表中。下面教你实现它:

 

1from iteration_utilities import deepflatten
2
3# if you only have one depth nested_list, use this
4def flatten(l):
5  return [item for sublist in l for item in sublist]
6
7l = [[1,2,3],[3]]
8print(flatten(l))
9# [1, 2, 3, 3]
10
11# if you don't know how deep the list is nested
12l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
13
14print(list(deepflatten(l, depth=3)))
15# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Numpy flatten 能够更好的处理你格式化好的数据。

 

随机取样

 

下面的例子中,使用 random 库,实现了从列表中随机取样。

 

1import random
2
3my_list = ['a', 'b', 'c', 'd', 'e']
4num_samples = 2
5
6samples = random.sample(my_list,num_samples)
7print(samples)

随机取样,我推荐使用 secrets 库来实现,更安全。下面的代码片断只能在 Python 3 中运行:

 

1import secrets                              # imports secure module.
2secure_random = secrets.SystemRandom()      # creates a secure random object.
3
4my_list = ['a','b','c','d','e']
5num_samples = 2
6
7samples = secure_random.sample(my_list, num_samples)
8
9print(samples)

 

数字化

 

下面代码将一个整形数转成一个数字化的对象:

 

1num = 123456
2
3list_of_digits = list(map(int, str(num)))
4
5print(list_of_digits)
6# [1, 2, 3, 4, 5, 6]

 

惟一性检查

 

下面的代码示例,能够检查列表中的元素是不是不重复的:

 

1def unique(l):2    if len(l)==len(set(l)):3        print("All elements are unique")4    else:5        print("List has duplicates")67unique([1,2,3,4])8# All elements are unique910unique([1,1,2,3])11# List has duplicates

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息