1.交换两个数字
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
输出
10 20
20 10
2.反转字符串
a ="GeeksForGeeks"
print("Reverse is", a[::-1])
输出
Reverse is skeeGroFskeeG
3.连接列表中的元素
a = ["Geeks", "For", "Geeks"]
print(" ".join(a))
输出
Geeks For Geeks
4.多比较符
n = 10
result = 1 < n < 20
print(result)
result = 1 > n <= 9
print(result)
输出
True
False
5.输出模块的位置
import os;
import socket;
print(os)
print(socket)
输出
<module 'os' from '/usr/lib/python3.5/os.py'>
<module 'socket' from '/usr/lib/python3.5/socket.py'>
6.使用枚举
class MyName:
Geeks, For, Geeks = range(3)
print(MyName.Geeks)
print(MyName.For)
print(MyName.Geeks)
输出
2
1
2
7.函数返回多个值
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
输出
1 2 3 4
8.找到数组中出现频率最高的数
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
输出
4
9.检查对象占用内存大小
import sys
x = 1
print(sys.getsizeof(x))
输出
28
10.检查两个字符串是否字谜(字母和出现次数一致)
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
print(is_anagram('geek', 'eegk'))
print(is_anagram('geek', 'peek'))
输出
True
False
文章到此就结束啦,如果你喜欢今天的Python 实战教程,请持续关注Python实用宝典,如果对你有帮助,麻烦在下面点一个赞/在看哦,有任何问题都可以在下方留言区留言,我们会耐心解答的!
Python实用宝典 (pythondict.com)
不只是一个宝典
欢迎关注公众号:Python实用宝典
原文来自Python实用宝典: Python 十个加快编程效率的技巧