你们知道今天聊聊关于 Python 一行代码的神奇之处!!!
复制
decimal = int('1010', 5) print(decimal) #130
1.
2.
输出:
复制
130
1.
转换大写字母
复制
# 转换大小写字母 str = "hi Python".upper() print(str) #HI PYTHON
1.
2.
3.
输出:
复制
HI PYTHON
1.
转换小写字母
复制
# 转换小写字母 str_lower1 = "HI PYTHON".lower() print(str_lower1) str_lower2 = "HI PYTHON".casefold() print(str_lower2)
1.
2.
3.
4.
5.
6.
输出:
复制
hi python hi python
1.
2.
复制
import math fact_5 = math.factorial(5) print(fact_5)
1.
2.
3.
4.
输出:
复制
120
1.
复制
words = ['Hello', 'Python', 'Hello', 'world'] print(max(words, key=len))
1.
2.
输出:
复制
Python
1.
复制
print("Hello, World!", file=open('test.txt', 'w'))
1.
复制
import time; print(time.ctime())
1.
2.
输出:
复制
Sun Oct 30 22:52:41 2021
1.
复制
test_str = ''.join(list(filter(lambda x: x.isalpha(), 'abc4532def4fg56vcg2'))) print(test_str)
1.
2.
输出:
复制
abcdeffgvcg
1.
复制
# 第一种方式 n = 50 sum_n1 = sum(range(0, n+1)) print(sum_n1) #第二种方式 sum_n2 = n*(n+1)//2 print(sum_n2)
1.
2.
3.
4.
5.
6.
7.
复制
print("hello python".count('l')) # 2
1.
复制
list(set['p','y','t','h','o','n'])
1.
复制
# d = {'five': 5, 'one': 1, 'four': 4, 'eight': 8} {key:d[key] for key in sorted(d.keys())} # {'eight': 8, 'five': 5, 'four': 4, 'one': 1}
1.
2.
3.
复制
# x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} # {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
1.
2.
3.
复制
list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] )) # [2, 4, 6]
1.
2.
关于 Python 小技巧-一行代码的操作还很多,后面咱们慢慢探索,希望大家一起进步。