程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

30个常用的Python代码片段(下)

hfteth 2025-05-28 17:22:31 技术文章 4 ℃

接上回,这篇文章我们来讲剩下的15个常用的Python代码片段

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)) # {'x': 1, 'y': 3, '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)) # {'x': 1, 'y': 3, '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, 'b': 3, 'c': 4}


21.枚举

list = ["a", "b", "c", "d"]
for index, element in enumerate(list): 
    print("Value", element, "Index ", index, )
# ('Value', 'a', 'Index ', 0)
# ('Value', 'b', 'Index ', 1)
# ('Value', 'c', 'Index ', 2)
# ('Value', 'd', 'Index ', 3)


22.计算执行特定代码所需的时间

import time


start_time = time.time()


a = 1
b = 2
c = a + b
print(c) #3


end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)# ('Time: ', 1.1205673217773438e-05)


23.将else子句作为try/except块的一部分,如果没有抛出异常则执行该子句。

try:
    2*3
except TypeError:
    print("An exception was raised")
else:
    print("Thank God, no exceptions were raised.")


#Thank God, no exceptions were raised.


24.返回列表中出现频率最高的元素

def most_frequent(list):
    return max(set(list), key = list.count)
  
numbers = [1,2,1,2,3,2,1,4,2]
most_frequent(numbers) #2


25.检查给定字符串是否为回文

def palindrome(a):
    return a == a[::-1] #a[::-1]会反序字符串


palindrome('mom') # True


26.不需要使用 if-else 条件的情况下编写一个简单的计算器

import operator
action = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul,
    "**": pow
}
print(action['-'](50, 25)) # 25


27.随机化列表中元素的顺序

from random import shuffle


foo = [1, 2, 3, 4]
shuffle(foo) #shuffle就地工作,并返回None
print(foo) # [1, 4, 3, 2] , foo = [1, 2, 3, 4]


28.展平

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret


spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]


29.无需使用额外变量交换两个变量值

a, b = -1, 14
a, b = b, a


print(a) # 14
print(b) # -1


30.获取缺失键的默认值

d = {'a': 1, 'b': 2}


print(d.get('c', 3)) # 3


以上就是所有的内容了,感谢关注!


如果有其他问题可以通过公众号【python玩转】联系作者

Tags:

最近发表
标签列表