python超实用的30 个简短的代码片段(二)

2022-10-08,,,,

python是目前最流行的语言之一,它在数据科学、机器学习、web开发、脚本编写、自动化方面被许多人广泛使用。

它的简单和易用性造就了它如此流行的原因。

如果你正在阅读本文,那么你或多或少已经使用过python或者对python感兴趣。

ps:如有需要python学习资料的小伙伴可以加点击下方链接自行获取http://t.cn/a6zvjdun

在本文中,我们将会介绍 30 个简短代码片段,你可以在 30 秒或更短的时间里理解和学习这些代码片段。

11.逗号分隔

以下代码段可将字符串列表转换为单个字符串,列表中的每个元素用逗号分隔。

hobbies = ["basketball", "football", "swimming"]
print("my hobbies are: " + ", ".join(hobbies)) # my hobbies are: basketball, football, swimming

12.计算元音字母数

以下方法可计算字符串中元音字母(‘a’, ‘e’, ‘i’, ‘o’, ‘u’)的数目。

import re    
def count_vowels(str):    
    return len(len(re.findall(r'[aeiou]', str, re.ignorecase)))    
count_vowels('foobar') # 3    
count_vowels('gym') # 0

13.首字母恢复小写

以下方法可用于将给定字符串的第一个字母转换为小写。

def decapitalize(string):    
    return str[:1].lower() + str[1:]    
decapitalize('foobar') # 'foobar'    
decapitalize('foobar') # 'foobar'

14.平面化

以下方法使用递归来展开潜在的深度列表。

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret
def deep_flatten(lst):
    result = []
    result.extend(
        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

15.差异

该方法只保留第一个迭代器中的值,从而发现两个迭代器之间的差异。

def difference(a, b):
    set_a = set(a)
    set_b = set(b)
    comparison = set_a.difference(set_b)
    return list(comparison)
difference([1,2,3], [1,2,4]) # [3]

16.寻找差异

下面的方法在将给定的函数应用于两个列表的每个元素后,返回两个列表之间的差值。

def difference_by(a, b, fn):
    b = set(map(fn, b))
    return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]

17.链式函数调用

以下方法可在一行中调用多个函数。

def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9

18.检查重复值

以下方法使用 set() 方法仅包含唯一元素的事实来检查列表是否具有重复值。

def has_duplicates(lst):
    return len(lst) != len(set(lst))
    
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # true
has_duplicates(y) # false

19.合并两个词典

以下方法可用于合并两个词典。

def merge_two_dicts(a, b):
    c = a.copy()   # make a copy of a 
    c.update(b)    # modify keys and values of a with the ones from b
    return c
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}

在python 3.5及更高版本中,你还可以执行以下操作:

def merge_dictionaries(a, b)
   return {**a, **b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}

20.将两个列表转换成一个词典

以下方法可将两个列表转换成一个词典。

def to_dictionary(keys, values):
    return dict(zip(keys, values))
    
keys = ["a", "b", "c"]    
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}

2020年最新python教程:

如果你处于想学python或者正在学习python,python的教程不少了吧,但是是最新的吗?

说不定你学了可能是两年前人家就学过的内容,在这小编分享一波2020最新的python教程。

 

 

以上这些教程小编已经为大家打包准备好了,希望对正在学习的你有所帮助!

获取方式,私信小编 “ 资料 ”,即可免费获取哦!

《python超实用的30 个简短的代码片段(二).doc》

下载本文的Word格式文档,以方便收藏与打印。