12 个用于日常编程的杀手级 Python 代码片段

开发 后端
在今天的文章中,我将与您分享12 个日常编程使用的Python代码片段,无需编写长代码即可解决问题,从而更好、更智能地编写代码。因此,不要再浪费时间了,让我们开始吧。

1、正则表达式

正则表达式是 Python 中匹配模式、搜索和替换字符串、验证字符串等的最佳技术。现在,您无需为此类工作使用循环和列表。

查看以下关于验证电子邮件格式的正则表达式片段代码示例:

# Regular Expression Check Mail
import re
def Check_Mail(email):
pattern = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
if re.fullmatch(pattern, email):
print("valid")
else:
print("Invalid")
Check_Mail("codedev101@gmail.com") #valid
Check_Mail("codedev101-haider@uni.edu") #Invalid
Check_Mail("code-101-work@my.net") # Invalid

2、Pro Slicing

这个简单的代码片段将帮助您像专业人士一样对列表进行切片。查看下面的示例代码:

# Pro Slicing
# list[start:end:step]
mylist = [1, 2, 3, 5, 5, 6, 7, 8, 9, 12]
mail ="codedev-medium@example.com"
print(mylist[4:-3]) # 5 6 7
print(mail[8 : 14]) # medium

3、Swap without Temp

您是否使用 Temp 变量来交换两个数据,而不是在 Python 中您不需要使用它?在此代码段中,我将与您分享如何在不使用 temp 的情况下交换两个数据变量。

查看下面的代码:

# Swap without Temp
i = 134
j = 431
[i, j] = [j, i]
print(i) #431
print(j) #134

4、Magic of F-string

我们可能使用 format() 方法或“%”方法来格式化字符串中的变量。这段代码将向您介绍 F 字符串,它比另一种格式要好得多。

看看下面的示例代码:

# Magic of f-String
# Normal Method
name = "Codedev"
lang = "Python"
data = "{} is writing article on {}".format(name, lang)
print(data)
# Pro Method with f-string
data = f"{name} is writing article on {lang}"
print(data

5、获取索引

现在您不再需要 Loop 来查找特定元素的索引。您可以使用列表中的 index() 方法来完成。

查看下面的代码:

# Get Index
x = [10 ,20, 30, 40, 50]
print(x.index(10)) # 0
print(x.index(30)) # 4
print(x.index(50)) # 2

6、基于Another List的排序列表

此代码段将向您展示如何根据另一个列表对列表进行排序。当您需要根据所需的位置进行排序时,此代码段非常方便。

# Sort List based on another List
list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]
list2 = [ 0, 1, 1, 1, 2, 2, 0, 1, 1, 3, 4]
C = [x for _, x in sorted(zip(list2, list1), key=lambda pair: pair[0])]
print(C) # ['a', 'g', 'b', 'c', 'd', 'h', 'i', 'e', 'f', 'j', 'k']

7、 反转字典

现在您不需要循环来反转任何字典。此代码段代码将在第二次尝试该代码段代码时反转字典。

# Invert the Dictionary
def Invert_Dictionary(data):
return {value: key for key, value in data.items()}
data = {"A": 1, "B":2, "C": 3}
invert = Invert_Dictionary(data)
print(invert) # {1: 'A', 2: 'B', 3: 'C'}

8、多线程

多线程将帮助您同时并行运行 Python 函数。假设您想同时执行 5 个函数,而无需等待每个函数完成。

查看下面的代码段:

# Multi-threading
import threading
def func(num):
for x in range(num):
print(x)
if __name__ == "__main__":
t1 = threading.Thread(target=func, args=(10,))
t2 = threading.Thread(target=func, args=(20,))
t1.start()
t2.start()
t1.join()
t2.join()

9、列表中出现最多的元素

此片段代码将简单地计算列表中出现次数最多的元素。我已经展示了两种方法来做到这一点。

在下面查看它:

# Element Occur most in List
from collections import Counter
mylst = ["a", "a", "b", "c", "a", "b","b", "c", "d", "a"]
# Method 1
def occur_most1(mylst):
return max(set(mylst), key=mylst.count)
print(occur_most1(mylst)) # a
# Method 2
# Much Faster then Method 1
def occur_most2(mylst):
data = Counter(mylst)
return data.most_common(1)[0][0]
print(occur_most2(mylst)) # a

10、分割线

有一个逐行格式的原始文本,并希望将其分成几行。此代码段将在一秒钟内解决您的问题。

# Split lines
data1 = """Hello to
Python"""
data2 = """Programming
Langauges"""
print(data1.split("\n")) # ['Hello to', 'Python']
print(data2.split("\n")) # ['Programming', ' Langauges']

11、 将列表映射到字典

此代码段将帮助您将任意两个列表转换为字典格式。要了解它是如何工作的,请查看下面的代码:

# Map List into Dictionary
def Convert_to_Dict(k, v):
return dict(zip(k, v))
k = ["a", "b", "c", "d", "e"]
v = [1, 2, 3, 4, 5]
print(Convert_to_Dict(k, v)) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

12、解析电子表格

现在您不需要 Pandas 或任何其他外部 Python 包来解析电子表格。Python 有一个内置的 CSV 模块,这段代码将向您展示如何使用它。

# Parse Spreadsheet
import csv
#Reading
with open("test.csv", "r") as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
file.close()
#Writing
header = ["ID", "Languages"]
csv_data = [234, "Python", 344, "JavaScript", 567, "Dart"]
with open("test2.csv", 'w', newline="") as file:
csv_writer = csv.writer(file)
csv_writer.writerow(header)
csv_writer.writerows(csv_data)
责任编辑:庞桂玉 来源: Python编程学习圈
相关推荐

2022-09-16 09:11:30

C++代码编程

2015-11-02 09:25:07

jQuery代码片段

2021-09-29 08:59:49

Rust编程语言

2022-10-20 15:16:23

JavaScript数组技能

2023-06-14 15:51:48

JavaScript

2018-07-23 08:19:26

编程语言Python工具

2020-06-23 07:48:18

Python开发技术

2023-07-17 15:28:03

JavaScrip开发

2024-01-02 22:12:15

Go代码片段Golang

2019-03-27 08:32:26

边缘计算网络

2014-10-13 11:30:14

2014-11-05 09:34:06

开源监测工具

2013-03-25 10:36:20

Android解决问题代码片段

2022-10-24 00:38:36

RustCLI工具

2011-11-23 09:21:43

jQuery

2023-10-12 15:02:21

PythonPandas数据分析

2023-04-10 14:49:35

Web应用程序工具

2023-12-06 18:06:37

Git开发

2023-12-21 18:01:58

Docker容器部署

2023-12-03 18:26:25

IDEA插件
点赞
收藏

51CTO技术栈公众号