您当前的位置: 首页 >  Python

嗨学编程

暂无认证

  • 0浏览

    0关注

    1405博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

超实用的 30 段 Python 案例(三)

嗨学编程 发布时间:2019-10-31 15:49:28 ,浏览量:0

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

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

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

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

21.使用枚举

以下方法将字典作为输入,然后仅返回该字典中的键。

'''
python学习交流群:1136201545更多学习资料可以加群获取
'''
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.Try else 指令

你可以将 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)
  
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)
25.回文

以下方法可检查给定的字符串是否为回文结构。该方法首先将字符串转换为小写,然后从中删除非字母数字字符。最后,它会将新的字符串与反转版本进行比较。

def palindrome(string):
    from re import sub
    s = sub('[W_]', '', string.lower())
    return s == s[::-1]
palindrome('taco cat') # True
26.没有 if-else 语句的简单计算器

以下代码段将展示如何编写一个不使用 if-else 条件的简单计算器。

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

以下算法通过实现 Fisher-Yates算法 在新列表中进行排序来将列表中的元素顺序随机打乱。

from copy import deepcopy
from random import randint
def shuffle(lst):
    temp_lst = deepcopy(lst)
    m = len(temp_lst)
    while (m):
        m -= 1
        i = randint(0, m)
        temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
    return temp_lst
  
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
28.列表扁平化

以下方法可使列表扁平化,类似于JavaScript中的[].concat(…arr)。

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.变量交换

以下是交换两个变量的快速方法,而且无需使用额外的变量。

def swap(a, b):
  return b, a
a, b = -1, 14
swap(a, b) # (14, -1)
30.获取缺失键的默认值

以下代码段显示了如何在字典中没有包含要查找的键的情况下获得默认值。

'''
python学习交流群:1136201545更多学习资料可以加群获取
'''
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3
关注
打赏
1663681728
查看更多评论
立即登录/注册

微信扫码登录

0.0520s