处理用户的多个输入
# bad practice码
n1 = input("enter a number : ")
n2 = input("enter a number : ")
n2 = input("enter a number : ")
print(n1, n2, n3)
# good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)
处理多个条件语句
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.")
# 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.")
判断数字奇偶性
print('odd' if int(input('Enter a number: '))%2 else 'even')
交换变量
v1 = 100
v2 = 200
# bad practice
temp = v1
v1 = v2
v2 = temp
v1 = 100
v2 = 200
# good practice
v1, v2 = v2, v1
判断字符串是否为回文串
print("John Deo"[::-1])
反转字符串
v1 = "madam" # is a palindrome string
v2 = "master" # is not a palindrome string
print(v1.find(v1[::-1]) == 0) # True
print(v1.find(v2[::-1]) == 0) # False
尽量使用 Inline if statement
name = "ali"
age = 22
# bad practices
if name:
print(name)
if name and age > 18:
print("user is verified")
# a better approach
print(name if name else "")
""" here you have to define the else condition too"""
# good practice
name and print(name)
age > 18 and name and print("user is verified")
删除list中的重复元素
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中重复最多的元素
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)
list 生成式
numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]
cities = ['London', 'Dublin', 'Oslo']
def visit(city):
print("Welcome to "+city)
for city in cities:
visit(city)
使用*args传递多个参数
def sum_of_squares(n1, n2)
return n1**2 + n2**2
print(sum_of_squares(2,3))
# output: 13
"""
what ever if you want to pass, multiple args to the function
as n number of args. so let's make it dynamic.
"""
def sum_of_squares(*args):
return sum([item**2 for item in args])
# now you can pass as many parameters as you want
print(sum_of_squares(2, 3, 4))
print(sum_of_squares(2, 3, 4, 5, 6))
在循环时处理下标
lst = ["blue", "lightblue", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)
拼接list中多个元素
names = ["john", "sara", "jim", "rock"]
print(", ".join(names))
将两个字典进行合并
d1 = {"v1": 22, "v2": 33}
d2 = {"v2": 44, "v3": 55}
d3 = {**d1, **d2}
print(d3)
{'v1': 22, 'v2': 44, 'v3': 55}
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
字典按照value进行排序
d = {
"v1": 80,
"v2": 20,
"v3": 40,
"v4": 20,
"v5": 10,
}
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
print(sorted_d)
from operator import itemgetter
sorted_d = dict(sorted(d.items(), key=itemgetter(1)))
sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))
from pprint import pprint
data = {
"name": "john deo",
"age": "22",
"address": {"contry": "canada", "state": "an state of canada :)", "address": "street st.34 north 12"},
"attr": {"verified": True, "emialaddress": True},
}
print(data)
pprint(data)
{'name': 'john deo', 'age': '22', 'address': {'contry': 'canada', 'state': 'an state of canada :)', 'address': 'street st.34 north 12'}, 'attr': {'verified': True, 'emialaddress': True}}
{'address': {'address': 'street st.34 north 12',
'contry': 'canada',
'state': 'an state of canada :)'},
'age': '22',
'attr': {'emialaddress': True, 'verified': True},
'name': 'john deo'}
# 使用切片
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist[::-1]'
1000000 loops, best of 5: 15.6 usec per loop
# 使用reverse()
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist.reverse()'
1000000 loops, best of 5: 10.7 usec per loop
作者:佚名 来源:Python开发者
本文为 @ 场长 创作并授权 21CTO 发布,未经许可,请勿转载。
内容授权事宜请您联系 webmaster@21cto.com或关注 21CTO 公众号。
该文观点仅代表作者本人,21CTO 平台仅提供信息存储空间服务。