python高级思路写法

一、处理多个条件语句

all()方法

对于all()的一般例子如下:

size = "lg"
color = "blue"
price = 50
# bad practice
if size == "lg" and color == "blue" and price < 100:
    print("Yes, I want to but the product.")

更好的处理方法如下:

# good practice
conditions = [
    size == "lg",
    color == "blue",
    price < 100,
]
if all(conditions):
    print("Yes, I want to but the product.")

对于any()的一般例子如下:

# bad practice
size = "lg"
color = "blue"
price = 50
if size == "lg" or color == "blue" or price < 100:
    print("Yes, I want to but the product.")

更好的处理方法如下:

# good practice
conditions = [
    size == "lg",
    color == "blue",
    price < 100,
]
if any(conditions):
    print("Yes, I want to but the product.")

 

二、list去重

 set() 来删除重复元素

lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
print(lst)
unique_lst = list(set(lst))
print(unique_lst)

 

三、找到list中重复最多的元素

用 max( ) 函数

lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
most_repeated_item = max(lst, key=lst.count)
print(most_repeated_item)

 

四、直接取多个数组元素赋值

line=[1,2]
a,content = line
print(a,content)
#1 2

 

https://mp.weixin.qq.com/s/qyadrP-r6SnuHiGtw4TiuQ

posted @ 2023-10-10 11:04  凯宾斯基  阅读(21)  评论(0编辑  收藏  举报