衡量运行时间

很多时候你需要计算某段代码执行所需的时间,可以使用 time 模块来实现这个功能。

import time

startTime = time.time()

# write your code or functions calls

endTime = time.time()
totalTime = endTime - startTime

print("Total time required to execute code is =", totalTime)

# output
Total time required to execute code is = 4.76837158203125e-07

获取两个列表之间的差异

不使用循环,找出两个列表的差异,可以使用集合的 symmetric_difference 方法。

list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
list2 = ['Scott', 'Eric', 'Kelly']

set1 = set(list1)
set2 = set(list2)

list3 = list(set1.symmetric_difference(set2))
print(list3)

# output
['Emma', 'Smith']

翻转字符串和列表

a = "zhihu"
print("Reverse is", a[::-1])
List = ["Shriya", "Lavina", "Sampreeti" ]
List.reverse()
print(List)

# output
Reverse is uhihz
['Sampreeti', 'Lavina', 'Shriya']

连接列表中的多个字符串

需要调用字符串的 join 方法,还可以设置间隔符,下面为间隔符为空格的例子。

a = ["Python", "Is", "Great"] 
print(" ".join(a))

# output
Python Is Great

同时使用多个比较运算符

在 C 中不能连续进行大小比较,在 Python 中就可以。

n = 10
result = 1 < n < 20
print(result) 
result = 1 < n <= 9
print(result)

# output
True
False

打印导入模块的文件路径

import os 
import socket 

print(os) 
print(socket)

# output
<module 'os' from 'D:\Users\xxx\miniconda3\envs\xin\lib\os.py'>
<module 'socket' from 'D:\Users\xxx\miniconda3\envs\xin\lib\socket.py'>

二维列表转一维列表

只需使用 Itertools 一行代码,即可将嵌套列表转换为一个列表。

import itertools  
a = [[1, 2], [3, 4], [5, 6]] 
print(list(itertools.chain.from_iterable(a))) 

# output
[1, 2, 3, 4, 5, 6]

Lambda 匿名函数用法

要声明一些小功能,但不使用常规的声明方式,可以用使用 lambda。 python 中的 lambda 关键字为声明匿名函数提供了快捷方式。

subtract = lambda x, y : x-y
subtract(5, 4)
# 可结合map reduce使用

列表中每个元素出现次数

Counter(list).most_common(n) 根据列表 / 字符串中每个元素出现次数,降序返回列表 / 字符串中的前 n 个元素,其中 n 是指定的数字。在元组中返回各个元素及其出现的次数。

# Code to find top 3 elements and their counts 
# using most_common 
from collections import Counter 
  
arr = [1, 3, 4, 1, 2, 1, 1, 3, 4, 3, 5, 1, 2, 5, 3, 4, 5] 
counter = Counter(arr) 
top_three = counter.most_common(3) 
print(top_three) 

# output
[(1, 5), (3, 4), (4, 3)]

输出结果为个数最多的 3 个数字,其中 1 出现 5 次,3 出现 4 次,4 出现 3 次。

找到列表中最常出现的值

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] 
print(max(set(test), key = test.count))
# max(test, key = test.count) 也可以实现同样功能,但列表数据量大时会变慢
# s.count(x) x在s中出现的总次数
# output
4

检查对象的内存使用情况

当你要使用任何数据结构(例如列表,字典或任何对象)来存储值或记录时,可以检查数据结构使用了多少内存。

使用 sys 模块中定义的 sys.getsizeof 函数获取内置对象使用的内存,返回对象的大小(以字节为单位)。

import sys 
x = 1
print(sys.getsizeof(x)) 

# output
28

注意:sys.getsizeof 不会为第三方对象或用户定义的对象返回正确的值。

字符串乘法拼接

n = 3
a = "Python"
print(a * n)

# output
PythonPythonPython

将多个列表同一位置元素zip在一起

当你需要连接许多迭代器对象(如列表)以获取单个列表时,可以使用 zip 函数,结果显示每个新列表每个元素,是所有迭代器对象同一位置值的元组。

Year = (1999, 2003, 2011, 2017)
Month = ("Mar", "Jun", "Jan", "Dec")
Day = (11,21,13,5)
print(zip(Year, Month, Day))

# output
[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]

.get获取字典中key对应的值,不存在则返回指定值

通过 [] 方式获取字典中的值时,如果键不存在则会报错,可以使用字典的 get 函数,指定键不存在时,可以返回的值。

比如字典中有键 ‘c’,则返回对应的值,否则返回 3。

d = {'a':1, 'b':2}
print(d.get('c', 3))

# output
3

for...else...

Python 中的 for 循环可以使用 else 关键字,如果在 for 循环中遇到 break 跳出循环,则不执行 else 子句,否则执行。

for i in range(5):
    pass
else:
    pass

{**d1, **d2}合并字典

d1 = {'a': 1}
d2 = {'b': 2}
print({**d1, **d2})

# output
{'a': 1, 'b': 2}

求列表中前 n 个最大 / 最小的数字

使用 heapq 返回任何列表中的前 n 个最小 / 最大元素,这里 n 是指定的数字。

# Python code to find 3 largest and 4 smallest
# elements of a list.
import heapq
  
grades = [110, 25, 38, 49, 20, 95, 33, 87, 80, 90]
print(heapq.nlargest(3, grades))
print(heapq.nsmallest(4, grades))

# output
[110, 95, 90]
[20, 25, 33, 38]

输出的第一行给出列表等级中存在的最大数字中的 3 个。 同样,输出的第二行将打印出列表等级中存在的最小元素中的 4 个,此功能的另一个特点是它不会忽略重复值。

x, y = y, x 就地交换两个数字

x, y = 10, 20
print(x, y) 
x, y = y, x 
print(x, y) 

# output
10 20
20 10

set(listNumbers)从列表中删除重复项

listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]
print("Original= ", listNumbers)

listNumbers = list(set(listNumbers))
print("After removing duplicate= ", listNumbers)

# output
Original=  [20, 22, 24, 26, 28, 28, 20, 30, 24]
After removing duplicate=  [20, 22, 24, 26, 28, 30]

比较两个无序列表

假设你有两个包含相同元素的列表,但是两个列表中的元素顺序都不同。可以使用 collections.Counter()方法进行判断,确定它们是否元素值都相同。

from collections import Counter

one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]

print("two lists are equal.", Counter(one) == Counter(two))

# output
two lists are equal.

检查列表中的所有元素是否唯一

def isUnique(item):
    tempSet = set()
    return not any(i in tempSet or tempSet.add(i) for i in item)

listOne = [123, 345, 456, 23, 567]
print("All List elemtnts are Unique ", isUnique(listOne))

listTwo = [123, 345, 567, 23, 567]
print("All List elemtnts are Unique ", isUnique(listTwo))

# output
All List elemtnts are Unique  True
All List elemtnts are Unique  False

字节转换为字符串

要将字节转换为字符串,可以对 bytes 对象进行解码以生成字符串。

byteVar = b"pynative"
str = str(byteVar.decode("utf-8"))
print("Byte to string is" , str )

# output
Byte to string is pynative

dict(zip(ItemId, names))将两个列表转换成字典

例如你有两个列表,一个列表包含键,第二个列表包含对应的值,想将这两个列表转换为一个字典。可以使用 zip 函数来进行实现。

ItemId = [54, 65, 76]
names = ["Hard Disk", "Laptop", "RAM"]

itemDictionary = dict(zip(ItemId, names))

print(itemDictionary)

# output
{54: 'Hard Disk', 65: 'Laptop', 76: 'RAM'}

设置小数位格式

你要显示带有 2 个小数位的任何浮点数。 例如 73.4(73.40)和 288.5400(88.54)。

number= 88.2345
print('{0:.2f}'.format(number))

s.ljust(10, '-') 字符串左对齐填充到10

左对齐函数 ljust 和右对齐函数 rjust,都需要指定字符串长度,以及想要填充的字符,不指定则默认填充空格。

s = "12345"
print(s.ljust(10, '-'))
print(s.rjust(10, '0'))

# output
12345-----
0000012345

https://www.zhihu.com/people/zhao-xiao-de-93/posts

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/qftie/p/16294106.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!