坐地铁,就能学会的100个 “非常有用” 的Python技巧【一】
菜鸟学Python
共 2570字,需浏览 6分钟
·
2021-11-28 12:21
作者:Fatos Morina 编译:ronghuaiyang
1. “for” 循环中的“Else”条件
numbers = [2, 4, 6, 8, 1]
for number in numbers:
if number % 2 == 1:
print(number)
break
else:
print("No odd numbers")
2. 使用命名的变量从列表中取元素
my_list = [1, 2, 3, 4, 5]
one, two, three, four, five = my_list
3. 使用heapq从列表中获取最大或最小的元素
import heapq
scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]
print(heapq.nlargest(3, scores)) # [91, 87, 82]
print(heapq.nsmallest(5, scores)) # [15, 33, 33, 49, 51]
4. 把列表中的值作为参数传递给方法
my_list = [1, 2, 3, 4]
print(my_list) # [1, 2, 3, 4]
print(*my_list) # 1 2 3 4
def sum_of_elements(*arg):
total = 0
for i in arg:
total += i
return total
result = sum_of_elements(*[1, 2, 3, 4])
print(result) # 10
5. 获取列表的所有中间元素
_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]
print(elements_in_the_middle) # [2, 3, 4, 5, 6, 7]
6. 一行赋值多个变量
one, two, three, four = 1, 2, 3, 4
7. 列表推导
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num * num for num in numbers]
print(squared_numbers)
dictionary = {'a': 4, 'b': 5}
squared_dictionary = {key: num * num for (key, num) in dictionary.items()}
print(squared_dictionary) # {'a': 16, 'b': 25}
8. 通过Enum枚举相同概念的相关项
Enum是绑定到唯一值的一组符号名。它们类似于全局变量,但它们提供了更有用的repr()、分组、类型安全和其他一些特性。
from enum import Enum
class Status(Enum):
NO_STATUS = -1
NOT_STARTED = 0
IN_PROGRESS = 1
COMPLETED = 2
print(Status.IN_PROGRESS.name) # IN_PROGRESS
print(Status.COMPLETED.value) # 2
9. 不使用循环来重复字符串
name = "Banana"
print(name * 4) # BananaBananaBananaBanana
10. 像数学式子一样比较3个数字
1 < x < 10
11. 在单条语句中合并字典
first_dictionary = {'name': 'Fatos', 'location': 'Munich'}
second_dictionary = {'name': 'Fatos', 'surname': 'Morina','location': 'Bavaria, Munich'}
result = first_dictionary | second_dictionaryprint(result) # {'name': 'Fatos', 'location': 'Bavaria, Munich', 'surname': 'Morina'}
12. 在tuple中找到元素的索引
books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')
print(books.index('Mastery')) # 3
13. 把字符串列表转换成一个列表
input = "[1,2,3]"
input = [1,2,3]
input = [[1, 2, 3], [4, 5, 6]]
import ast def string_to_list(string):
return ast.literal_eval(string)
import ast
def string_to_list(string):
return ast.literal_eval(string)
string = "[[1, 2, 3],[4, 5, 6]]"
my_list = string_to_list(string)
print(my_list) # [[1, 2, 3], [4, 5, 6]]
14. 使用命名参数避免 “trivial” 错误
a - b != b -a
def subtract(a, b):
return a - b
print((subtract(1, 3))) # -2
print((subtract(3, 1))) # 2
def subtract(a, b):
return a - b
print((subtract(a=1, b=3))) # -2
print((subtract(b=3, a=1))) # -2
15. 使用单个print()语句打印多个元素
print(1, 2, 3, "a", "z", "this is here", "here is something else")
16. 一行打印多个元素
print("Hello", end="")
print("World") # HelloWorld
print("Hello", end=" ")
print("World") # Hello World
print('words', 'with', 'commas', 'in', 'between', sep=', ')
# words, with, commas, in, between
17. 打印多个值,每个值之间使用自定义分隔符
print("29", "01", "2022", sep="/") # 29/01/2022
print("name", "domain.com", sep="@") # name@domain.com
18. 不能在变量名的开头使用数字
four_letters = “abcd” # this works4_letters = “abcd” # this doesn’t work
19. 不能在变量名的开头使用操作符
+variable = “abcd” # this doesn’t work
20. 你不能把0作为数字的第一个数字
number = 0110 # this doesn't work
21. 你可以在变量名的任何位置使用下划线字符
a______b = "abcd" # this works
_a_b_c_d = "abcd" # this also works
22. 可以用下划线分隔较大的数字
print(1_000_000_000) # 1000000000
print(1_234_567) # 1234567
23. 颠倒列表的顺序
my_list = ['a', 'b', 'c', 'd']
my_list.reverse()
print(my_list) # ['d', 'c', 'b', 'a']
24. 使用step函数对字符串切片
my_string = "This is just a sentence"
print(my_string[0:5]) # This
# Take three steps forward
print(my_string[0:10:3]) # Tsse
25. 反向切片
my_string = "This is just a sentence"
print(my_string[10:0:-1]) # suj si sih
# Take two steps forward
print(my_string[10:0:-2]) # sjs i
26. 只有开始或结束索引的部分切片
my_string = "This is just a sentence"
print(my_string[4:]) # is just a sentence
print(my_string[:3]) # Thi
27. Floor 除法
print(3/2) # 1.5
print(3//2) # 1
28. == 和 “is” 的差别
first_list = [1, 2, 3]
second_list = [1, 2, 3]
# Is their actual value the same?
print(first_list == second_list) # True
# Are they pointing to the same object in memory
print(first_list is second_list)
# False, since they have same values, but in different objects in memory
third_list = first_list
print(third_list is first_list)
# True, since both point to the same object in memory
29. 更改分配给另一个变量的变量的值
first = "An initial value"
second = first
first = "An updated value"
print(first) # An updated value
print(second) # An initial value
30. 检查一个字符串是否大于另一个字符串
first = "abc"
second = "def"
print(first < second) # True
second = "ab"
print(first < second) # False
31. 检查字符串是不是从特定字符开始的
my_string = "abcdef"
print(my_string.startswith("b")) # False
32. 使用id()找到变量的唯一id
print(id(1)) # 4325776624
print(id(2)) # 4325776656
print(id("string")) # 4327978288
33. Integers, floats, strings, booleans, sets以及tuples是不可修改的
number = 1
print(id(number)) # 4325215472
print(id(1)) # 4325215472
number = 3
print(id(number)) # 4325215536
print(id(1)) # 4325215472
送你一张我们星球的优惠券,目前已经有100多人啦,还有3天就过期了!
欢迎来一起玩Python!
推荐阅读:
入门: 最全的零基础学Python的问题 | 零基础学了8个月的Python | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 | 从万众期待到口碑扑街!唐探3令人失望 | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏 | 九宫格 | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!| 再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|
年度爆款文案
评论