网站首页 > 基础教程 正文
Python拥有独特且易于学习的语法。下面提供了一些最重要的Python技巧。你可以将这些技巧添加到你的Python技能库中。
1. 将字符串转换为列表
string = "TechGeekBuzz"
print(list(string))
['T', 'e', 'c', 'h', 'G', 'e', 'e', 'k', 'B', 'u', 'z', 'z']
2. 反转字符串
string = "TechGeekBuzz"
print(string[ : :-1])
zzuBkeeGhceT
3.列表创建为字符串
my_list = ['this', "is", "an", "article","from", "TechGeekBuzz"]
print("-".join(my_list))
this-is-an-article-from-TechGeekBuzz
4. 根据索引值,结合两个可迭代对象
a = ['one', 'two','three']
b = [1 , 2 , 3 ]
c= zip(a,b)
print(list(c))
[('one', 1), ('two', 2), ('three', 3)]
5. 从可迭代对象中获取最大值最小值
my_list = [1, 2, 3,200,12,362]
print("Max is:", max(my_list))
print("Minimum value is:",min(my_list))
Max is: 362
Minimum value is: 1
6. 执行写在字符串中的命令
string = 'print("The sum of 10+10 is:", 10+10)'
eval(string)
The sum of 10+10 is: 20
7. 制作一个长度为0到N的列表
n= 20
my_list = list(range(0,n,2))
print(my_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
8.列出字符串的所有子字符串
main = "hello"
substrings = [main[i: j] for i in range(len(main)) for j in range(i + 1, len(main) + 1)]
print(substrings)
['h', 'he', 'hel', 'hell', 'hello', 'e', 'el', 'ell', 'ello', 'l', 'll', 'llo', 'l', 'lo', 'o']
9. 转置矩阵
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = list(zip(*matrix))
print(transpose)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
10. 合并多个字典
a = {'a':2, 'A':50}
b = {'b':4, 'B':34}
c = {'c':2, 'C':45}
combine = {**a, **b, **c}
print(combine)
{'a': 2, 'A': 50, 'b': 4, 'B': 34, 'c': 2, 'C': 45}
猜你喜欢
- 2024-11-01 【Python】十个必备 Python与操作系统交互命令实践
- 2024-11-01 python操作文件和目录 python文件目录操作方法
- 2024-11-01 Python执行系统命令的四种方法 python执行操作系统命令
- 2024-11-01 对Python命令式编程与符号编程的理解
- 2024-11-01 python的print命令 python print指令
- 2024-11-01 总结归纳的 Django 基本命令 django使用教程
- 2024-11-01 跟我一起学Python——window操作系统常用Dos命令
- 2024-11-01 Python 命令行之旅:使用 docopt 实现 git 命令
- 2024-11-01 python常用命令及操作语句 python基本用法
- 2024-11-01 Google 开源的 Python 命令行库:深入 fire(二)
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)