0
点赞
收藏
分享

微信扫一扫

30个python小技巧,精美~



翻译:AI_study

欢迎关注公主号:AI算法与图像处理

30个python小技巧,精美~_字符串

Photo by Jantine Doornbos on Unsplash

python代表了许多人在数据科学和机器学习、web开发、脚本编写、自动化等领域使用的最流行的语言之一。

这种流行的部分原因是它简单易学。

如果您正在阅读本文,那么很可能您已经使用了python,或者至少对它感兴趣。

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

  1. All unique

以下方法检查给定列表是否有重复的元素。它使用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]
all_unique(x) # False
all_unique(y) # True

  1. Anagrams(相同字母异序词)

此方法可用于检查两个字符串是否为anagram。anagram是通过重新排列不同单词或短语的字母而形成的单词或短语,通常只使用所有原始字母一次。

from collections import Counter

def anagram(first, second):
return Counter(first) == Counter(second)


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

  1. Memory

此代码段可用于检查对象的内存使用情况。

import sys 

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

  1. Byte size

此方法返回字符串的长度(字节)。

def byte_size(string):
return(len(string.encode('utf-8')))


byte_size('?') # 4
byte_size('Hello World') # 11

  1. Print a string N times

此代码段可用于打印字符串n次,而无需使用循环。

n = 2; 
s ="Programming";

print(s * n); # ProgrammingProgramming

  1. Capitalize first letters

此代码片段只使用方法title()将字符串中每个单词的首字母大写。

s = "programming is awesome"

print(s.title()) # Programming Is Awesome

  1. Chunk

此方法将列表分为指定大小的较小列表。

def chunk(list, size):
return [list[i:i+size] for i in range(0,len(list), size)]

  1. Compact

此方法使用filter()从列表中删除错误值(False、None、0和“”)。

def compact(lst):
return list(filter(bool, lst))


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

  1. Count by

此片段可用于转置二维数组。

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

  1. Chained comparison

您可以在一行中对各种运算符进行多次比较。

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

  1. Comma-separated

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

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

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

  1. Get vowels

此方法获取字符串中的元音(“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') # []

  1. Decapitalize

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

def decapitalize(str):
return str[:1].lower() + str[1:]


decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # 'fooBar'

  1. Flatten

以下方法使用递归展开潜在的高维列表(deep list)。

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

def 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_list


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

  1. Difference

此方法只保留第一个可迭代对象(Iterables)中的值,从而查找两个可迭代对象之间的差异。

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]

  1. Difference by

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

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 }]

  1. Chained function call

您可以在一行内调用多个函数。

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

  1. Has duplicates

下面的方法使用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

  1. Merge two dictionaries

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

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}

在Python3.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}

  1. Convert two lists into a dictionary

以下方法可用于将两个列表转换为字典。

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}

  1. Use 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)

  1. Time spent

此代码段可用于计算执行特定代码所需的时间。

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)

  1. 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.

  1. Most frequent

此方法返回列表中出现频率最高的元素。

def most_frequent(list):
return max(set(list), key = list.count)


numbers = [1,2,1,2,3,2,1,4,2]
most_frequent(numbers)

  1. Palindrome

此方法检查给定字符串是否为回文。

def palindrome(a):
return a == a[::-1]


palindrome('mom') # True

  1. Calculator without if-else

下面的代码片段展示了如何编写一个简单的计算器,而无需使用if-else条件。

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

  1. Shuffle

此片段可用于随机化列表中元素的顺序。注意,shuffle在适当的位置工作,并且不返回任何值。

from random import shuffle

foo = [1, 2, 3, 4]
shuffle(foo)
print(foo) # [1, 4, 3, 2] , foo = [1, 2, 3, 4]

  1. Spread

此方法将类似于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]

  1. Swap values

一种非常快速的交换两个变量的方法,而不必使用另一个变量。

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

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

  1. Get default value for missing keys

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

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

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

这是一个简短的片段列表,你可以在日常工作中找到有用的片段。它高度基于这个github存储库,在这个存储库中,您可以在python和其他语言和技术中找到许多其他有用的代码片段。

​​https://github.com/30-seconds/30_seconds_of_knowledge​​


举报

相关推荐

0 条评论