人生苦短,快学Python!
使用这些有用的 Python 代码片段提升你的编程技能,在本文中,我将分享 10 个 Python 代码片段,以帮助你应对日常编程挑战,你可能已经知道其中一些片段,但其他片段对你来说,有可能是新的。我们现在开始吧。
1. 简单的 HTTP Web 服务器
# Simple HTTP SERVER
import socketserver
import http.server
PORT = 8000
handler = http.server.SimpleHTTPRequestHandler
with 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 List
mylist = [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 Dictionary
mydict = {1: "Python", 2: "JavaScript", 3: "Csharp"}
mydict.update({4: "Dart"})
print(mydict) # {1: 'Python', 2: 'JavaScript', 3: 'Csharp', 4: 'Dart'}
4.拆分多行字符串
# Split Multi Lines String
string = "Data \n is encrpted \n by Python"
print(string)
# Output
# Data
# is encrpted
# by Python
splited = string.split("\n")
print(splited) # ['Data ', ' is encrpted ', ' by Python']
5. 跟踪列表中元素的频率
# Track Frequency
import collections
def 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 Creation
import csv
with 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 String
mylist = ["I learn", "Python", "JavaScript", "Dart"]
string = " ".join(mylist)
print(string) # I learn Python JavaScript Dart
8. 获取任何数据的类型
# Get Type of Any Data
data1 = 123
data2 = "Py"
data3 = 123.443
data4 = True
data5 = [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'>
9.修改打印功能
# 修改打印功能
print("Top Programming Languages are %r, %r and %r" % ('Py', 'Js', 'C#'))
# Output
# Top Programming Languages are 'Py', 'Js' and 'C#'
10. 获取数据占用的内存
# Get Memory taken by data
import sys
def memory(data):
return sys.getsizeof(data)
print(memory(100)) # 28
print(memory("Pythonnnnnnn")) # 61
以上就是我今天跟你分享的10个Python的代码片段,希望你能发现这些 Python 代码片段它们的有用之处,并且用起来很有趣,然后,随时与你的程序员朋友分享这篇文章。