Skip to main content
 Web开发网 » 编程语言 » Python语言

20个python极简代码,非常实用

2021年11月26日5530百度已收录

本文为大家分享20个简短的python代码,非常实用,能帮助你更快掌握python!

一.字节占用

下面的代码块可以检查字符串占用的字节数。

1.def byte_size(string):

2.return(len(string.encode('utf-8')))

3.byte_size('') # 4

4.byte_size('Hello World') # 11

二.大写第一个字母

以下代码块会使用 title() 方法,从而大写字符串中每一个单词的首字母。

1.s = "programming is awesome"

2.print(s.title())

3.

4.# Programming Is Awesome

3.内存占用

1.import sys

2.variable = 30

3.print(sys.getsizeof(variable)) # 24

三.字符元素组成判定

检查两个字符串的组成元素是不是一样的。

1.from collections import Counter

2.def anagram(first, second):

3.return Counter(first) == Counter(second)

4.anagram("abcd3", "3acdb") # True

四.重复元素判定

以下方法可以检查给定列表是不是存在重复元素,它会使用 set() 函数来移除所有重复元素。

1.def all_unique(lst):

2.return len(lst)== len(set(lst))

3.x = [1,1,2,2,3,2,3,4,5,6]

4.y = [1,2,3,4,5]

5.all_unique(x) # False

6.all_unique(y) # True

五.链式对比

我们可以在一行代码中使用不同的运算符对比多个不同的元素。

1.a = 3

2.print( 2 < a < 8) # True

3.print(1 == a < 2) # False

六.解包

如下代码段可以将打包好的成对列表解开成两组不同的元组。

1.array = [['a', 'b'], ['c', 'd'], ['e', 'f']]

2.transposed = zip(*array)

3.print(transposed)

4.

5.# [('a', 'c', 'e'), ('b', 'd', 'f')]

七.压缩

这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。

1.def compact(lst):

2.return list(filter(bool, lst))

3.compact([0, 1, False, 2, '', 3, 'a', 's', 34])

4.

5.# [ 1, 2, 3, 'a', 's', 34 ]

20个python极简代码,非常实用  Python常用代码 第1张

八.分块

给定具体的大小,定义一个函数以按照这个大小切割列表。

1.from math import ceil

2.def chunk(lst, size):

3.return list(

4.map(lambda x: lst[x * size:x * size + size],

5.list(range(0, ceil(len(lst) / size)))))

6.chunk([1,2,3,4,5],2)

7.

8.# [[1,2],[3,4],5]

九.大写第一个字母

以下代码块会使用 title() 方法,从而大写字符串中每一个单词的首字母。

1.s = "programming is awesome"

2.print(s.title())

3.

4.# Programming Is Awesome

十.打印 N 次字符串

该代码块不需要循环语句就能打印 N 次字符串。

1.n = 2

2.s ="Programming"

3.print(s * n)

4.

5.# ProgrammingProgramming

十一.将两个列表转化为字典

如下方法将会把两个列表转化为单个字典。

1.def to_dictionary(keys, values):

2.return dict(zip(keys, values))

3.keys = ["a", "b", "c"]

4.values = [2, 3, 4]

5.print(to_dictionary(keys, values))

6.

7.#{'a': 2, 'c': 4, 'b': 3}

十二.合并两个字典

下面的方法将用于合并两个字典。

1.def merge_two_dicts(a, b):

2.c = a.copy() # make a copy of a

3.c.update(b) # modify keys and values of a with the once from b

4.return c

5.a={'x':1,'y':2}

6.b={'y':3,'z':4}

7.print(merge_two_dicts(a,b))

8.#{'y':3,'x':1,'z':4}

9在 Python 3.5 或更高版本中,我们也可以用以下方式合并字典:

10.def merge_dictionaries(a, b)

11.return {**a, **b}

12.a = { 'x': 1, 'y': 2}

13.b = { 'y': 3, 'z': 4}

14.print(merge_dictionaries(a, b))

15.

16.# {'y': 3, 'x': 1, 'z': 4}

十三.检查重复项

如下代码将检查两个列表是不是有重复项。

1.def has_duplicates(lst):

2.return len(lst) != len(set(lst))

3.x = [1,2,3,4,5,5]

4.y = [1,2,3,4,5]

5.has_duplicates(x) # True

6.has_duplicates(y) # False

十四.链式函数调用

你可以在一行代码内调用多个函数。

1.def add(a, b):

2.return a + b

3.def subtract(a, b):

4.return a - b

5.a, b = 4, 5

6.print((subtract if a > b else add)(a, b)) # 9

20个python极简代码,非常实用  Python常用代码 第2张

十五.链式函数调用

你可以在一行代码内调用多个函数。

1.def add(a, b):

2.return a + b

3.def subtract(a, b):

4.return a - b

5.a, b = 4, 5

6.print((subtract if a > b else add)(a, b)) # 9

十六.通过函数取差

如下方法首先会应用一个给定的函数,然后再返回应用函数后结果有差别的列表元素。

1.def difference_by(a, b, fn):

2.b = set(map(fn, b))

3.return [item for item in a if fn(item) not in b]

4.from math import floor

5.difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]

6.difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])

7.

8.# [ { x: 2 } ]

十七.逗号连接

下面的代码可以将列表连接成单个字符串,且每一个元素间的分隔方式设置为了逗号。

1.hobbies = ["basketball", "football", "swimming"]

2.print("My hobbies are: " + ", ".join(hobbies))

3.

4.# My hobbies are: basketball, football, swimming

十八.元音统计

以下方法将统计字符串中的元音 (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) 的个数,它是通过正则表达式做的。

1.import re

2.def count_vowels(str):

3.return len(len(re.findall(r'[aeiou]', str, 4.re.IGNORECASE)))

4.count_vowels('foobar') # 3

5.count_vowels('gym') # 0

十九.首字母小写

如下方法将令给定字符串的第一个字符统一为小写。

1.def decapitalize(string):

2.return str[:1].lower() + str[1:]

3.decapitalize('FooBar') # 'fooBar'

4.decapitalize('FooBar') # 'fooBar'

二十.展开列表

该方法将通过递归的方式将列表的嵌套展开为单个列表。

1.def spread(arg):

2.ret = []

3.for i in arg:

4.if isinstance(i, list):

5.ret.extend(i)

6.else:

7.ret.append(i)

8.return ret

9.def deep_flatten(lst):

10.result = []

11.result.extend(

12.spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))

13.return result

14.deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

20个python极简代码,非常实用  Python常用代码 第3张

更多python知识请持续关注我

欢迎点赞,收藏,转发。

评论列表暂无评论
发表评论
微信