你必须知道的常用的足够简练的Python代码

许多程序员喜欢Python,因为它的语法简单简洁。下面提供的这些 Python 代码足够简练,可用于解决常见问题。


1.提取字典的键值对

dict1 = {'A':33, 'B':43, 'C':88, 'D':56}
# 提取字典中值大于50的键值对
dict2 = { key:value for key, value in dict1.items() if value > 50 }
print(dict2)

set1 = {'A','C'}
# 提取字典中键包含在集合中的键值对
dict3 = { key:value for key,value in dict1.items() if key in set1 }
print(dict3)

「输出:」

{'C': 88, 'D': 56} {'A': 33, 'C': 88}

2.搜索和替换文本

可以使用 str.replace() 方法搜索和替换字符串中的文本。

str1 = "http://www.zbxx.net"
str1 = str1.replace("http", "https")
print(str1)

「输出:」

https://www.zbxx.net

对于更复杂的搜索替换,可以使用 re 模块。Python 中的正则表达式可以使复杂的任务变得更加容易。

3.过滤列表元素

可以使用列表推导式根据特定条件过滤列表中的元素。

list1 = [12, 56, 34, 76, 79]
# 提取列表中大于50的元素
list2 = [i for i in list1 if i>50]
print(list2)

「输出:」

[56, 76, 79]

4.对齐字符串

可以使用 ljust()、rjust() 和 center() 方法对齐字符串。 可以实现左对齐、右对齐及使字符串在给定宽度的范围居中对齐。

str1 = "Python"
print(str1.ljust(10))
print(str1.center(10))
print(str1.rjust(10))

「输出:」

Python
  Python
    Python

还可以使用字符填充。

str1 = "Python"
print(str1.ljust(10, '#'))
print(str1.center(10, '#'))
print(str1.rjust(10, '#'))

「输出:」

Python####

##Python##

####Python

5.将序列拆解为单独的变量

可以使用赋值运算符将任何序列拆解到变量中,只要变量的数量和序列的元素数量相互匹配。

tup1 = (1, 2, 3)
a, b, c = tup1
print(a,b,c)

「输出:」

1 2 3

6.任意数量参数的函数

自定义函数中,需要使用 “*” 来接受任意数量的参数。

def mysum(value1,*value):
    s=value1+sum(value)
    print(s)
mysum(10, 10)
mysum(10, 10, 10)

「输出:」

20 30

7. 反向迭代

可以使用 reversed() 函数、range() 函数和切片技术以相反的顺序迭代序列。

list1 = [1, 2, 3, 4, 5, 6]
for i in reversed(list1):
    print(i,end='')
list1 = [1, 2, 3, 4, 5, 6]
for i in range(len(list1) -1, -1, -1):
    print(list1[i],end='')
list1 = [1, 2, 3, 4, 5, 6]
for i in list1[::-1]:
    print(i,end='')

「输出:」

654321

8.写入尚不存在的文件

如果只想在文件不存在时才写入该文件,则需要在 x 模式(独占创建模式)下打开该文件。

with open('abc.txt', 'x') as f:
    f.write('Python')

如果文件已经存在,则此代码将导致 Python 出错:FileExistsError。

文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!

猜你喜欢

转载自blog.csdn.net/Rocky006/article/details/131007202