50条有趣的Python一行代码,建议收藏!
大家好,我是 Jack。
在学习Python的过程中,总会发现Python能够轻易的解决许多问题。
一些复杂的任务,甚至可以使用一行Python代码就能搞定。
下面,小F给大家介绍50个有趣的Python一行代码,都很实用。
希望大家能从中找到对自己有帮助的技巧。
▍1、字母异位词
两个单词如果包含相同的字母,次序不同,则称为字母易位词(anagram)。
例如,“silent”和“listen”是字母易位词,而“apple”和“aplee”不是易位词。
from
collections
import Counter
s1 =
'below's2 =
'elbow'print(
'anagram')
if Counter(s1) == Counter(s2)
else print(
'not an anagram')
使用一行Python代码,就能判断出来了。
▍2、二进制转十进制
decimal = int(
'1010',
2)
print(decimal)
#10▍3、将字符串转换为小写
print(
"Hi my name is XiaoF".lower())
# 'hi my name is xiaof'
print(
"Hi my name is XiaoF".casefold())
# 'hi my name is xiaof'
▍4、将字符串转换为大写
print(
"hi my name is XiaoF".upper())
# 'HI MY NAME IS XIAOF'
▍5、将字符串转换为字节
print(
"convert string to bytes using encode method".encode())
# b'convert string to bytes using encode method'
▍6、拷贝文件
import
shutil
shutil.copyfile(
'source.txt',
'dest.txt')
▍7、快速排序
qsort =
lambda l: l
if len(l) <=
1else qsort([x
for x
in l[
1:]
if x < l[
0]]) + [l[
0]] + qsort([x
for x
in l[
1:]
if x >= l[
0]])
print(qsort([
17,
29,
11,
97,
103,
5]))
# [5, 11, 17, 29, 97, 103]
▍8、n个连续数的和
n =
10print(sum(range(
0, n+
1)))
# 55
▍9、交换两个变量的值
a,b = b,a
▍10、斐波纳契数列
fib =
lambda x: x
if x<=
1else fib(x
-1) + fib(x
-2)
print(fib(
20))
# 6765
▍11、将嵌套列表合并为一个列表
main_list = [[
0,
1,
2], [
11,
12,
13], [
52,
53,
54]]
result = [item
for sublist
in main_list
for item
in sublist]
print(result)
>
[
0,
1,
2,
11,
12,
13,
52,
53,
54]
▍12、运行一个HTTP服务器
python3 -m http.server
8000python2 -m SimpleHTTPServer
▍13、反转列表
numbers = [
0,
1,
2,
11,
12,
13,
52,
53,
54]
print(numbers[::
-1])
# [54, 53, 52, 13, 12, 11, 2, 1, 0]
▍14、阶乘
import
# 120
math
fact_5 = math.factorial(
5)
print(fact_5)
# 120
▍15、在列表推导式中使用for和if
even_list = [number
for number
in [
1,
2,
3,
4]
if number %
2 ==
0]
print(even_list)
# [2, 4]
▍16、列表中最长的字符串
words = [
'This',
'is',
'a',
'list',
'of',
'words']
result = max(words, key=len)
print(result)
# 'words'
▍17、列表推导式
li = [num
for num
in range(
0,
10)]
print(li)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
▍18、集合推导式
num_set = {num
for num
in range(
0,
10)}
print(num_set)
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
▍19、字典推导式
dict_numbers = {x: x*x
for x
in range(
1,
5)}
print(dict_numbers)
# {1: 1, 2: 4, 3: 9, 4: 16}
▍20、if-else
print(
"even")
if4 %
2==
0else print(
"odd")
▍21、无限循环
while1
:
0▍22、检查数据类型
print(isinstance(
2, int))
# True
print(isinstance(
"allwin", str))
# True
print(isinstance([
3,
4,
1997], list))
# True
▍23、While循环
a =
5while
a >
0:
a = a -
1print(a)
# 0
▍24、使用print语句写入文件
print(
"Hello, World!", file=open(
'file.txt',
'w'))
既可打印出信息,还能将信息保存文件。
▍25、计算一个字符在字符串中出现的频率
print(
"umbrella".count(
'l'))
# 2
▍26、合并列表
list1 = [
1,
2,
4]
list2 = [
'XiaoF']
list1.extend(list2)
print(list1)
# [1, 2, 4, 'XiaoF']
▍27、合并字典
dict1 = {
'name':
'weiwei',
'age':
23}
dict2 = {
'city':
'Beijing'}
dict1.update(dict2)
print(dict1)
# {'name': 'weiwei', 'age': 23, 'city': 'Beijing'}
▍28、合并集合
set1 = {
0,
1,
2}
set2 = {
11,
12,
13}
set1.update(set2)
print(set1)
# {0, 1, 2, 11, 12, 13}
▍29、时间戳
import
time
print(time.time())
▍30、列表中出现次数最多的元素
test_list = [
9,
4,
5,
4,
4,
5,
9,
5,
4]
most_frequent_element = max(set(test_list), key=test_list.count)
print(most_frequent_element)
# 4
▍31、嵌套列表
numbers = [[num]
for num
in range(
10)]
print(numbers)
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
▍32、八进制转十进制
print(int(
'30',
8))
# 24
▍33、将键值对转换为字典
result = dict(name=
'XiaoF', age=
23)
print(result)
# {'name': 'XiaoF', 'age': 23}
▍34、求商和余数
quotient, remainder = divmod(
4,
5)
print(quotient, remainder)
# 0 4
divmod()函数返回当参数1除以参数2时,包含商和余数的元组。
▍35、删除列表中的重复项
print(list(set([
4,
4,
5,
5,
6])))
# [4, 5, 6]
▍36、按升序排序列表
print(sorted([
5,
2,
9,
1]))
# [1, 2, 5, 9]
▍37、按降序排序列表
print(sorted([
5,
2,
9,
1], reverse=
True))
# [9, 5, 2, 1]
▍38、获取小写字母表
import
# abcdefghijklmnopqrstuvwxyz
string
print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
▍39、获取大写字母表
import
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
string
print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
▍40、获取0到9字符串
string
print(string.digits)
# 0123456789▍41、十六进制转十进制
print(int(
'da9',
16))
# 3497
▍42、日期时间
import
# Thu Aug 13 20:00:00 2021
time
print(time.ctime())
# Thu Aug 13 20:00:00 2021
▍43、将列表中的字符串转换为整数
print(list(map(int, [
'1',
'2',
'3'])))
# [1, 2, 3]
▍44、用键对字典进行排序
d = {
'one':
1,
'four':
4,
'eight':
8}
result = {key: d[key]
for key
in sorted(d.keys())}
print(result)
# {'eight': 8, 'four': 4, 'one': 1}
▍45、用键值对字典进行排序
x = {
1:
2,
3:
4,
4:
3,
2:
1,
0:
0}
result = {k: v
for k, v
in sorted(x.items(), key=
lambda item: item[
1])}
print(result)
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
▍46、列表旋转
li = [
1,
2,
3,
4,
5]
# li[n:] + li[:n], 右变左
print(li[
2:] + li[:
2])
# [3, 4, 5, 1, 2]
# li[-n:] + li[:-n], 左变右
print(li[
-1:] + li[:
-1])
# [5, 1, 2, 3, 4]
▍47、将字符串中的数字移除
message =
''.join(list(filter(
lambda x: x.isalpha(),
'abc123def4fg56vcg2')))
print(message)
# abcdeffgvcg
▍48、矩阵变换
old_list = [[
1,
2,
3], [
3,
4,
6], [
5,
6,
7]]
result = list(list(x)
for x
in zip(*old_list))
print(result)
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]
▍49、列表过滤
result = list(filter(
lambda x: x %
2 ==
0, [
1,
2,
3,
4,
5,
6]))
print(result)
# [2, 4, 6]
▍50、解包
a, *b, c = [
1,
2,
3,
4,
5]
print(a)
# 1print(b)
# [2, 3, 4]print(c)
# 5推荐阅读
关键词
代码
字母
建议
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。