Python作为一种高级编程语言,允许你通过处理普通的编程任务来关注应用程序的核心功能。该编程语言的简单语法规则进一步使你更容易保持代码库的可读性和应用程序的可维护性。在这篇文章中,我介绍了一些技巧和窍门来帮助你更快地编码。这是35个简短的Python代码片段,可以作为你工作中的参考。
下面的代码片段将把一个整数转换成一个数字列表。
num = 123456
# using map
list_of_digits = list(map(int, str(num)))
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
# using list comprehension
list_of_digits = [int(x) for x in str(num)]
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
下面的函数用于检查一个字符串是否是回文。
def palindrome(string):
return string == string[::-1]
palindrome('python') # False
检查一个给定的字符串是否是Palindrome
我们已经讨论了如何逆转一个字符串。因此,在Python中,回文成为一个简单的程序。
my_string = "abcba"
if my_string == my_string[::-1]:
print("palindrome")
else:
print("not palindrome")
# Output
# palindrome
在其它语言中,要在两个变量之间交换数值而不使用第三个变量,我们必须使用算术运算符或位数XOR。在Python中,这要简单得多,如下所示。
a = 5
b = 10
a, b = b, a
print(a) # 10
print(b) # 5
Python 使得在两个变量之间交换值变得非常简单,而不需要使用另一个变量。
a = 1
b = 2
a, b = b, a
print(a) # 2
print(b) # 1
如果给定的数字是偶数,下面的函数返回True,否则返回False。
def is_even(num):
return num % 2 == 0
is_even(10) # True
以下函数可用于将一个多行字符串分割成一个行的列表。
def split_lines(s):
return s.split('
')
split_lines('50
python
snippets') # ['50', ' python', ' snippets']
我们可以使用字符串类中的.split()方法将一个字符串分割成一个子字符串列表。你也可以把你想分割的分隔符作为参数传给他。
string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"
# default separator ' '
print(string_1.split())
# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# defining separator as '/'
print(string_2.split('/'))
# ['sample', ' string 2']
标准库的sys模块提供了getsizeof()函数。该函数接受一个对象,调用该对象的sizeof()方法,并返回结果,因此你可以使你的对象可以被检查。
import sys
print(sys.getsizeof(5)) # 28
print(sys.getsizeof("Python")) # 55
Python 字符串库不支持内置的 reverse() ,就像其他 Python 容器(如 list)所做的那样。有许多方法来反转字符串,其中最简单的方法是使用切片操作符。
language = "python"
reversed_language = language[::-1]
print(reversed_language) # nohtyp
下面的片段使用Python的切片操作反转了一个字符串。
# Reversing a string using slicing
my_string = "ABCDE"
reversed_string = my_string[::-1]
print(reversed_string)
# Output
# EDCBA
在不使用循环的情况下,打印一个字符串n次是非常容易的,如下所示。
def repeat(string, n):
return (string * n)
repeat('python', 3) # pythonpythonpython
n = 3 # number of repetitions
my_string = "abcd"
my_list = [1,2,3]
print(my_string*n)
# abcdabcdabcd
print(my_list*n)
# [1,2,3,1,2,3,1,2,3]
下一个片段是将一个字符串列表合并为一个单一的字符串。
strings = ['50', 'python', 'snippets']
print(','.join(strings)) # 50,python,snippets
join()方法将一个作为参数传递的字符串列表合并成一个字符串。在我们的例子中,我们用逗号分隔符把它们分开。
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# Using join with the comma separator
print(','.join(list_of_strings))
# Output
# My,name,is,Chaitanya,Baweja
这个函数返回传递的列表中的第一个元素。
def head(list):
return list[0]
print(head([1, 2, 3, 4, 5])) # 1
我们还使用most_common()函数来获得列表中最频繁的元素。
# finding frequency of each element in a list
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 inpidual element
# 3
print(count.most_common(1)) # most frequent element
# [('d', 5)]
这个函数返回存在于两个列表中的每一个元素。
def union(a,b):
return list(set(a + b))
union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) # [1,2,3,4,5,6,8]
该函数返回存在于给定列表中的唯一元素。
def unique_elements(numbers):
return list(set(numbers))
unique_elements([1, 2, 3, 2, 4]) # [1, 2, 3, 4]
这个函数返回一个列表中两个或多个数字的平均值。
def average(*args):
return sum(args, 0.0) / len(args)
average(5, 8, 2) # 5.0
这个函数检查一个列表中的所有元素是否是唯一的。
def unique(list):
if len(list)==len(set(list)):
print("All elements are unique")
else:
print("List has duplicates")
unique([1,2,3,4,5]) # All elements are unique
Python 计数器可以跟踪容器中每个元素的频率。Counter() 返回一个以元素为键、以其出现的频率为值的字典。
from collections import Counter
list = [1, 2, 3, 2, 4, 3, 2, 3]
count = Counter(list)
print(count) # {2: 3, 3: 3, 1: 1, 4: 1}
这个函数返回在一个列表中出现频率最高的元素。
def most_frequent(list):
return max(set(list), key = list.count)
numbers = [1, 2, 3, 2, 4, 3, 1, 3]
most_frequent(numbers) # 3
下一个函数用于将一个角度从度转换为弧度。
import math
def degrees_to_radians(deg):
return (deg * math.pi) / 180.0
degrees_to_radians(90) # 1.5707963267948966
下面的片段用于计算执行一段代码所需的时间。
import time
start_time = time.time()
a,b = 5,10
c = a+b
end_time = time.time()
time_taken = (end_time- start_time)*(10**6)
print("Time taken in micro_seconds:", time_taken) # Time taken in micro_seconds: 39.577484130859375
这个函数计算一个数字列表的最大公除数。
from functools import reduce
import math
def gcd(numbers):
return reduce(math.gcd, numbers)
gcd([24,108,90]) # 6
这个片段可用于查找一个字符串中存在的所有独特字符。
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)
Lambda是一个匿名函数,只能够容纳一个表达式。
x = lambda a, b, c : a + b + c
print(x(5, 10, 20)) # 35
这个函数返回对给定的iterable(list, tuple, etc.)的每一项应用给定函数后的结果列表。
def multiply(n):
return n * n
list = (1, 2, 3)
result = map(multiply, list)
print(list(result)) # {1, 4, 9}
这个函数借助于一个测试序列中每个元素是否为真的函数来过滤给定的序列。
arr = [1, 2, 3, 4, 5]
arr = list(filter(lambda x : x%2 == 0, arr))
print (arr) # [2, 4]
列表理解为我们提供了一种简单的方法来创建一个基于某些可迭代的列表。在创建过程中,可迭代的元素可以有条件地包含在新的列表中,并根据需要进行转换。
numbers = [1, 2, 3]
squares = [number**2 for number in numbers]
print(squares) # [1, 4, 9]
下面的片段通过将旧列表的每个元素乘以2来创建一个新列表。
# Multiplying each element in a list by 2
original_list = [1,2,3,4]
new_list = [2*x for x in original_list]
print(new_list)
# [2,4,6,8]
切片是用来从一个给定的序列中提取一个连续的序列或子序列的元素。下面的函数用于串联两个切片操作的结果。首先,我们将列表从索引d切到结尾,然后从开始切到索引d。
def rotate(arr, d):
return arr[d:] + arr[:d]
if name == '__main__':
arr = [1, 2, 3, 4, 5]
arr = rotate(arr, 2)
print (arr) # [3, 4, 5, 1, 2]
最后一个片段用于从一行中调用多个函数并评估结果。
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 5, 10
print((subtract if a > b else add)(a, b)) # 15
下面的片段可以用来将一个字符串转换为标题大小写。这是用字符串类的title()方法完成的。
my_string = "my name is chaitanya baweja"
# using the title() function of string class
new_string = my_string.title()
print(new_string)
# Output
# My Name Is Chaitanya Baweja
Python 中的错误处理可以使用 try/except 块轻松完成。在这个块中添加一个else语句可能是有用的。当 try 块中没有出现异常时,它就会运行。
如果你需要在没有异常的情况下运行某些东西,请使用finally。
a, b = 1,0
try:
print(a/b)
# exception raised when b is 0
except ZeroDivisionError:
print("pision by zero")
else:
print("no exceptions raised")
finally:
print("Run this always")
下面的脚本使用enumerate来遍历一个列表中的值以及它们的索引。
my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):
print('{0}: {1}'.format(index, value))
# 0: a
# 1: b
# 2: c
# 3: d
# 4: e
下面的脚本可以用来检查一个对象的内存使用情况。
import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28
在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)
# Output
# {'apple': 9, 'banana': 4, 'orange': 8}
下面的片段使用时间库来计算执行一段代码所需的时间。
import time
start_time = time.time()
# Code to check follows
a, b = 1,2
c = a+ b
# Code to check ends
end_time = time.time()
time_taken_in_micro = (end_time- start_time)*(10**6)
print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)
有时你不确定你的列表的嵌套深度,你只想把所有的元素放在一个单一的扁平列表中。
这里是你如何得到的:
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)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
下面的片段使用随机库从一个给定的列表中生成n个随机样本。
import random
my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2
samples = random.sample(my_list,num_samples)
print(samples)
# [ 'a', 'e'] this will have any 2 random values
有人向我推荐了secrets库,用于为密码学目的生成随机样本。下面的片段只在Python 3上工作。
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)
# [ 'e', 'd'] this will have any 2 random values
下面的函数将检查一个列表中的所有元素是否是唯一的。
def unique(l):
if len(l)==len(set(l)):
print("All elements are unique")
else:
print("List has duplicates")
unique([1,2,3,4])
# All elements are unique
unique([1,1,2,3])
# List has duplicates
我希望这个教程一定会对你有所帮助,如果你喜欢这个教程,请考虑与其他人分享。
页面更新:2024-05-14
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号