Python是当下最风行的语言之一,广泛应用于数据迷信和机器学习、网络开发、脚本、自动化等。

风行起因大略两点:

  • 简略性,优雅简洁,无废话代码
  • 易学性,疾速上手,对老手敌对

上面,给大家分享30个简短的python代码,感触下如何在30秒或更短时间内疾速实现乏味的工作。欢送珍藏、关注,点赞反对!

“没被java伤,怎知Python好”。有些情理,必须亲自试一试,刚才晓得,比方什么叫:“人生苦短,我用Python~"。

1. 列表值惟一

应用set()转换函数,判断列表是否有反复的元素。

def all_unique(lst):    return len(lst) == len(set(lst))x = [1,1,2,2,3,2,3,4,5,6]y = [1,2,3,4,5]print(all_unique(x)) # Falseprint(all_unique(y)) # True

2. 变形词

判断两个字符串是否是变形词。变形词是指通过重新排列字母后,两个字符串能够相等。实质上每个字符呈现的次数一样。

from collections import Counterdef anagram(first, second):    return Counter(first) == Counter(second)anagram("abcd3", "3acdb") # True

3. 内存查看

查看一个对象的内存应用状况:

import sys variable = 30 print(sys.getsizeof(variable)) # 24

4. 字节大小

该办法以字节为单位返回一个字符串的长度。

def byte_size(string):    return(len(string.encode('utf-8')))        byte_size('') # 4byte_size('Hello World') # 11    

5. 打印字符串N次

上面代码疾速打印某个字符串N次,而不须要应用循环来实现。

n = 2s ="Programming"print(s * n) # ProgrammingProgramming

6. 首字母大写

简略地应用了title()办法,将字符串中每个单词的第一个字母大写。

s = "programming is awesome"print(s.title()) # Programming Is Awesome

7. 列表分块

上面办法将一个列表宰割成指定大小的小列表。

def chunk(list, size):    return [list[i:i+size] for i in range(0,len(list), size)]print(chunk([1, 2, 3, 4, 5, 6],2))# [[1, 2], [3, 4], [5, 6]]print(chunk([1, 2, 3, 4, 5, 6, 7],2))# [[1, 2], [3, 4], [5, 6], [7]]

8. filter疾速过滤

应用filter()办法从列表中过滤“假”值(False, None, 0"").

def compact(lst):    return list(filter(None, lst))    print(compact([0, 1, False, 2, '', 3, 'a', 's', 34]))# [ 1, 2, 3, 'a', 's', 34 ]

9. 数组转置

巧用zip()对一个二维数组进行转置。

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]transposed = zip(*array)print(list(transposed))# [('a', 'c', 'e'), ('b', 'd', 'f')]array = [['a', 'b', 'c'], ['d', 'e', 'f']]transposed = zip(*array)print(list(transposed))# [('a', 'd'), ('b', 'e'), ('c', 'f')]

10. 链式比拟

能够在一行中用各种运算符做多个比拟,妙法天然。

a = 3print( 2 < a < 8) # Trueprint(1 == a < 2) # False

11. join()链接

join()将字符串列表变成繁多的字符串, 列表中的每个元素都用逗号,离开。

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

12. 获取元音

上面代码获取字符串中元音('a', 'e', 'i', 'o', 'u')字母。

def get_vowels(string):    return [each for each in string if each in 'aeiou'] get_vowels('foobar') # ['o', 'o', 'a']get_vowels('gym') # []

13. 去首字母化

将字符串的第一个字母变成小写。

def decapitalize(str):    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 retdef deep_flatten(xs):    flat_list = []    [flat_list.extend(deep_flatten(x)) for x in xs] if isinstance(xs, list) else flat_list.append(xs)    return flat_listprint(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 floordifference_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 + bdef subtract(a, b):    return a - ba, b = 4, 5print((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]print(has_duplicates(x)) # Trueprint(has_duplicates(y)) # False

19. 合并字典

上面办法利用update()合并两个字典。

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 ca = { '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. 两列表转为字典

上面的办法用zip()dict()函数将两个列表转换为一个字典。

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}

21. 巧用enumerate

应用enumerate()来获取列表的值和索引。

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. 耗时统计

time.time()计算执行某段代码所需的工夫。

import timestart_time = time.time()a = 1b = 2c = a + bprint(c) #3end_time = time.time()total_time = end_time - start_timeprint("Time: ", total_time)# ('Time: ', 1.1205673217773438e-05)

23. try-else

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

try:    2*3except 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]print(most_frequent(numbers))# 2  

25. 回文判断

查看给定的字符串是否是一个回文。

def palindrome(a):    return a == a[::-1]print(palindrome('mom')) # Trueprint(palindrome('pythontip')) # False

26. 简略计算器

编写一个简略的计算器,而不须要应用if-else条件。

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

27. 随机洗牌

random.shuffle()随机化一个列表中的元素程序。留神shuffle在原地工作, 并返回None

from random import shufflefoo = [1, 2, 3, 4]shuffle(foo) print(foo) # [1, 4, 3, 2] , foo = [1, 2, 3, 4]

28. 列表开展

相似于JavaScript中的[].concat(...arr),将一个列表扁平化,留神上面代码不能对深层嵌套列表扁平化。

def spread(arg):    ret = []    for i in arg:        if isinstance(i, list):            ret.extend(i)        else:            ret.append(i)    return retprint(spread([1,2,3,[4,5,6],[7],8,9]))# [1,2,3,4,5,6,7,8,9]print(spread([1,2,3,[4,5,6],[7],8,9,[10,[11]]]))# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, [11]]

29. 变量替换

一个十分疾速的替换两个变量的办法,不须要应用额定的变量。

a, b = -1, 14a, b = b, aprint(a) # 14print(b) # -1

30. 字典默认值

应用dict.get(key,default)在要找的键不存在字典中的时返回默认值。

d = {'a': 1, 'b': 2}print(d.get('a', 3)) # 1print(d.get('c', 3)) # 3

大节

下面分享的30个python乏味代码,心愿对大家有用。

如果感觉还能够,点赞珍藏,坏蛋毕生安全 。

pythontip 出品,Happy Coding!

公众号: 夸克编程

加vx: pythontip,谈天说地,聊Python