分享

20 个 解决日常编程问题的Python 代码片段

 天选小丑 2022-10-01 发布于广西

(给有课网加星标,开发与培养你的第二职业能力)

使用这些有用的 Python 代码片段提升你的编程技能,在本文中,我将分享 20 个 Python 代码片段,以帮助你应对日常编程挑战,你可能已经知道其中一些片段,但其他片段对你来说,有可能是新的。

我们现在开始吧。

1. 简单的 HTTP Web 服务器

# Simple HTTP SERVERimport socketserverimport http.serverPORT = 8000handler = http.server.SimpleHTTPRequestHandlerwith socketserver.TCPServer(('', PORT), handler) as http: print('Server Launch at Localhost: ' + str(PORT)) http.serve_forever()# Type in http://127.0.0.1:8000/ in your webbrowser

2.单行循环List

# One Liner Loop throught Listmylist = [10, 11, 12, 13, 14]print([i * 2 for i in mylist]) # [20, 22, 24, 26, 28]print([i * 5 for i in mylist]) # [50, 55, 60, 65, 70]

3.更新字典

# Update Dictionarymydict = {1: 'Python', 2: 'JavaScript', 3: 'Csharp'}mydict.update({4: 'Dart'})print(mydict) # {1: 'Python', 2: 'JavaScript', 3: 'Csharp', 4: 'Dart'}

4.拆分多行字符串

# Split Multi Lines Stringstring = 'Data \n is encrpted \n by Python'print(string)# Output# Data# is encrpted# by Pythonsplited = string.split('\n')print(splited) # ['Data ', ' is encrpted ', ' by Python']

5. 跟踪列表中元素的频率

# Track Frequency import collectionsdef Track_Frequency(List): return dict(collections.Counter(List))print(Track_Frequency([10, 10, 12, 12, 10, 13, 13, 14]))# Output# {10: 3, 12: 2, 13: 2, 14: 1}

6. 不使用 Pandas 读取 CSV 文件

# Simple Class Creationimport csvwith open('Test.csv', 'r') as file:    read = csv.reader(f)    for r in read:        print(row)# Output# ['Sr', 'Name', 'Profession']# ['1', 'Haider Imtiaz', 'Back End Developer']# ['2', 'Tadashi Wong', 'Software Engineer']

7. 将列表压缩成一个字符串

# Squash list of Stringmylist = ['I learn', 'Python', 'JavaScript', 'Dart']string = ' '.join(mylist)print(string) # I learn Python JavaScript Dart

8. 获取列表中元素的索引

# Get Index of Element in Listmylist = [10, 11, 12, 13, 14]print(mylist.index(10)) # 0 print(mylist.index(12)) # 2print(mylist.index(14)) # 4

9. Magic of *arg

# Magic of *argdef func(*arg): num = 0 for x in arg: num = num + xprint(num) # 600func(100, 200, 300)

10. 获取任何数据的类型

# Get Type of Any Datadata1 = 123data2 = 'Py'data3 = 123.443data4 = Truedata5 = [1, 2]print(type(data1)) # <class 'int'>print(type(data2)) # <class 'str'>print(type(data3)) # <class 'float'>print(type(data4)) # <class 'bool'>print(type(data5)) # <class 'list'>

11.修改打印功能

# Modified Print Functionprint('Top Programming Languages are %r, %r and %r' % ('Py', 'Js', 'C#'))# Output# Top Programming Languages are 'Py', 'Js' and 'C#'

12. 字符串去大写

# Decapitilation of Stringdata1 = 'ABCD'data2 = 'Py'data3 = 'Learn Coding'print(data1.lower()) # abcdprint(data2.lower()) # pyprint(data3.lower()) # learn coding

13. 更快捷的变量交换方式

# Quick Way to Exchange Variablesd1 = 25d2 = 50d1, d2 = d2, d1print(d1, d2) # 50 25

14. 分色打印

# Print with Seperationprint('Py', 'Js', 'C#', sep='-') # Py-Js-C#print('100', '200', '300', sep='x') # 100x200x300

15. 获取网页 HTML 数据

# First Install Request with pip install requestsimport requestsr = requests.get('https:///@codedev101')print(r) # Whole page html data will display

16. 获取数据占用的内存

# Get Memory taken by dataimport sysdef memory(data):    return sys.getsizeof(data)print(memory(100)) # 28print(memory('Pythonnnnnnn')) # 61

17. 简单的类创建

# Simple Class Creationclass Employee: def __init__(self, empID): self.empID = empID self.name = 'Haider' self.salary = 50000
def getEmpData(self): return self.name, self.salaryemp = Employee(189345)print(emp.getEmpData()) # ('Haider', 50000)

18. 字符串乘法器


# String Multiplier# Normal way for x in range(5): print('C#')
# Good wayprint('C# '*5) # C# C# C# C# C#

19.进行链式比较

# Chain Comparisona = 5print(1 == a < 2) # Falseprint(2 < 3 < 6 > a) # True

20. 数字化整数值

# Digitizinginteger = 234553digitz = [int(i) for i in str(integer)]print(digitz) # [2, 3, 4, 5, 5, 3]

最后的想法

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多