关于python:Python中的七个小技巧

3次阅读

共计 1580 个字符,预计需要花费 4 分钟才能阅读完成。

  1. 引言
    Python 语言是令人惊叹的,语法简略,功能强大;把握其中的一些技巧能够改善咱们在 Python 中的编码格调。在本文中,咱们将介绍 Python 中不常见的七个技巧。
    闲话少说,咱们间接开始吧。
  2. 频率统计
    在 Python 中咱们不须要应用循环来计算列表中每个元素呈现的频率。更为不便的是,在 Python 中咱们能够应用其内置的 counter 函数来实现该性能。
    相干的样例代码如下:
# Count Frequency
import collections
lst = [1,2,3,2,2,4,4,4,5,6,7,7,7,5,3]
counter=collections.Counter(lst)
print(counter)
# output
# Counter({2: 3, 4: 3, 7: 3, 3: 2, 5: 2, 1: 1, 6: 1})
  1. 疾速格式化字符串
    在 Python 中咱们个别应用 format() 函数或者 % 来格式化字符串。然而这里举荐一种更快的形式来格式化须要输入的字符串,那就是应用 f -strings 来输入。
    相干样例代码如下:
# Fast way to Format String
w1 = "something"
w2 = "Daily"
data = f"Code is {w1} we should do {w2}"
print(data) # Code is something we should do Daily
  1. 读取 CSV 文件
    其实,咱们不肯定非要应用 Pandas 模块来读取和写入 CSV。咱们能够应用 Python 内置的 csv 模块实现相应的性能。
    相干样例代码如下:
# CSV Reading
import csv
with open('test.csv', 'r') as file:
    r = csv.reader(file)
    for row in r:
        print(row)
  1. 从门路中获取文件名
    接下来这个技巧能够不便地帮忙咱们从门路中获取相应的文件名。这对于须要实现从残缺门路中提取文件名的性能来说十分不便。
    相干样例代码如下:
# Get file name from Path
import os
filepath =  "/path/to/file.txt"
filename = os.path.basename(filepath)
print(filename) # file.txt
# file name without extension
print(filename.split(".")[0]) # file
  1. 正则表达式的魔力
    正则表达式是提取、匹配和搜寻文本数据中特定字符串的绝妙技巧。
    上面咱们无妨举一个从原始文本数据中提取电话号码的示例代码:
import re
# example 1
phn = "jajdasko;askj0234989835kfpwek"
r = re.findall("[0-9]", phn)
print("".join(r)) # 0234989835
  1. Print 函数暗藏的参数
    你晓得 Python 中的 print()函数有一些参数吗?
    在上面的示例代码中,总结了两个常见 Python 参数示例。代码如下:
# example 1
print("hello", end=" ")
print("world")
#output:
#hello world
# example 2
print("Python", "is", "somthing", "different", sep="#")
#output
#Python#is#somthing#different
  1. 迭代列表对
    这个简略的技巧能够帮忙咱们同时迭代两对列表。
    相干的样例代码如下:
# iterating pair of String
lst1 = ['a', 'b', 'c', 'd']
lst2 = ['1', '2', '3', '4']
for x, y in zip(lst1, lst2):
    print(x, y)
# output
# a 1
# b 2
# c 3
# d 4

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注 Python 技术大本营,获取更多技能与教程。

正文完
 0