20个好用到哭的Python代码段!!!(Python小技巧)

Python是一种非BS编程语言。设计简单和易读性是它广受欢迎的两大原因。正如Python的宗旨:美丽胜于丑陋,显式胜于隐式。

记住一些帮助提高编码设计的常用小诀窍是有用的。在必要时刻,这些小诀窍能够减少你上网查Stack Overflow的麻烦。而且它们会在每日编程练习中助你一臂之力。

1. 反转字符串

以下代码使用Python切片操作来反转字符串。



\# Reversing a string using slicing

  

my\_string = "ABCDE"

reversed\_string = my\_string\[::-1\]

  

print(reversed\_string)

  

\# Output

\# EDCBA


2. 使用标题类(首字母大写)

以下代码可用于将字符串转换为标题类。这是通过使用字符串类中的title()方法来完成。




my\_string = "my name is chaitanya baweja"

  

\# using the title() function of string class

new\_string = my\_string.title()

  

print(new\_string)

  

\# Output

\# My Name Is Chaitanya Baweja


3. 查找字符串的唯一要素

以下代码可用于查找字符串中所有的唯一要素。我们使用其属性,其中一套字符串中的所有要素都是唯一的。




my\_string = "aavvccccddddeee"

  

\# converting the string to a set

temp\_set = set(my\_string)

  

\# stitching set into a string using join

new\_string =   .join(temp\_set)

  

print(new\_string)


4. 输出 n次字符串或列表

你可以对字符串或列表使用乘法(*)。如此一来,可以按照需求将它们任意倍增。




n = 3 # number of repetitions

  

my\_string = "abcd"

my\_list = \[1,2,3\]

  

print(my\_string\*n)

\# abcdabcdabcd

  

print(my\_list\*n)

\# \[1,2,3,1,2,3,1,2,3\]

import streamlit as st  



一个有趣的用例是定义一个具有恒定值的列表,假设为零。




n = 4

my\_list = \[0\]\*n # n denotes the length of the required list

\# \[0, 0, 0, 0\]


5. 列表解析

在其他列表的基础上,列表解析为创建列表提供一种优雅的方式。

以下代码通过将旧列表的每个对象乘两次,创建一个新的列表。




\# Multiplying each element in a list by 2

  

original\_list = \[1,2,3,4\]

  

new\_list = \[2\*x for x in original\_list\]

  

print(new\_list)

\# \[2,4,6,8\]


6. 两个变量之间的交换值

Python可以十分简单地交换两个变量间的值,无需使用第三个变量。




a = 1

b = 2

  

a, b = b, a

  

print(a) # 2

print(b) # 1


7. 将字符串拆分成子字符串列表

通过使用.split()方法,可以将字符串分成子字符串列表。还可以将想拆分的分隔符作为参数传递。




string\_1 = "My name is Chaitanya Baweja"

string\_2 = "sample/ string 2"

  

\# default separator

print(string\_1.split())

\# \[ My ,  name ,  is ,  Chaitanya ,  Baweja \]

  

\# defining separator as  /

print(string\_2.split( / ))

\# \[ sample ,   string 2 \]


8. 将字符串列表整合成单个字符串

join()方法将字符串列表整合成单个字符串。在下面的例子中,使用comma分隔符将它们分开。




list\_of\_strings = \[ My ,  name ,  is ,  Chaitanya ,  Baweja \]

  

\# Using join with the comma separator

print( , .join(list\_of\_strings))

  

\# Output

\# My,name,is,Chaitanya,Baweja


9. 检查给定字符串是否是回文(Palindrome)

反转字符串已经在上文中讨论过。因此,回文成为Python中一个简单的程序。




my\_string = "abcba"

  

m	if my\_string == my\_string\[::-1\]:

    print("palindrome")

else:

    print("not palindrome")

  

\# Output

\# palindrome


10. 列表的要素频率

有多种方式都可以完成这项任务,而我最喜欢用Python的Counter 类。Python计数器追踪每个要素的频率,Counter()反馈回一个字典,其中要素是键,频率是值。

也使用most_common()功能来获得列表中的most_frequent element。




\# finding frequency of each element in a list

from collections import Counter

  

my\_list = \[ a , a , b , b , b , c , d , d , d , d , d \]

count = Counter(my\_list) # defining a counter object

  

print(count) # Of all elements

\# Counter({ d : 5,  b : 3,  a : 2,  c : 1})

  

print(count\[ b \]) # of individual element

\# 3

  

print(count.most\_common(1)) # most frequent element

\# \[( d , 5)\]


11. 查找两个字符串是否为anagrams

Counter类的一个有趣应用是查找anagrams。

anagrams指将不同的词或词语的字母重新排序而构成的新词或新词语。

如果两个字符串的counter对象相等,那它们就是anagrams。




From collections import Counter

  

str\_1, str\_2, str\_3 = "acbde", "abced", "abcda"

cnt\_1, cnt\_2, cnt\_3  = Counter(str\_1), Counter(str\_2), Counter(str\_3)

  

if cnt\_1 == cnt\_2:

    print( 1 and 2 anagram )

if cnt\_1 == cnt\_3:

    print( 1 and 3 anagram )


12. 使用try-except-else块

通过使用try/except块,Python 中的错误处理得以轻松解决。在该块添加else语句可能会有用。当try块中无异常情况,则运行正常。

如果要运行某些程序,使用 finally,无需考虑异常情况。




a, b = 1,0

  

try:

    print(a/b)

    # exception raised when b is 0

except ZeroDivisionError:

    print("division by zero")

else:

    print("no exceptions raised")

finally:

    print("Run this always")


13.使用列举获取索引和值对

以下脚本使用列举来迭代列表中的值及其索引。




my\_list = \[ a ,  b ,  c ,  d ,  e \]

  

for index, value in enumerate(my\_list):

    print( {0}: {1} .format(index, value))

  

\# 0: a

\# 1: b

\# 2: c

\# 3: d

\# 4: e


14. 检查对象的内存使用

以下脚本可用来检查对象的内存使用。




import sys

  

num = 21

  

print(sys.getsizeof(num))

  

\# In Python 2, 24

\# In Python 3, 28


15. 合并两个字典

在Python 2 中,使用update()方法合并两个字典,而Python3.5 使操作过程更简单。

在给定脚本中,两个字典进行合并。我们使用了第二个字典中的值,以免出现交叉的情况。




dict\_1 = { apple : 9,  banana : 6}  

dict\_2 = { banana : 4,  orange : 8}

  

combined\_dict = {\*\*dict\_1, \*\*dict\_2}

  

print(combined\_dict)

\# Output

\# { apple : 9,  banana : 4,  orange : 8}


16. 执行一段代码所需时间

下面的代码使用time 软件库计算执行一段代码所花费的时间。




import time  

  

start\_time = time.time()

\# Code to check follows

a, b = 1,2

c = a+ b

\# Code to check ends

end\_time = time.time()

time\_taken\_in\_micro = (end\_time- start\_time)\*(10\*\*6)

  

print(" Time taken in micro\_seconds: {0} ms").format(time\_taken\_in\_micro)


17. 列表清单扁平化

有时你不确定列表的嵌套深度,而且只想全部要素在单个平面列表中。

可以通过以下方式获得:




from iteration\_utilities import deepflatten

  

\# if you only have one depth nested\_list, use this

def flatten(l):

  return \[item for sublist in l for item in sublist\]

  

l = \[\[1,2,3\],\[3\]\]

print(flatten(l))

\# \[1, 2, 3, 3\]

  

\# if you don t know how deep the list is nested

l = \[\[1,2,3\],\[4,\[5\],\[6,7\]\],\[8,\[9,\[10\]\]\]\]

  

print(list(deepflatten(l, depth=3)))

\# \[1, 2, 3, 4, 5, 6, 7, 8, 9, 10\]


若有正确格式化的数组,Numpy扁平化是更佳选择。

18. 列表取样

通过使用random软件库,以下代码从给定的列表中生成了n个随机样本。




import random  

  

my\_list = \[ a ,  b ,  c ,  d ,  e \]

num\_samples = 2

  

samples = random.sample(my\_list,num\_samples)

print(samples)

\# \[  a ,  e \] this will have any 2 random values


强烈推荐使用secrets软件库生成用于加密的随机样本。

以下代码仅限用于Python 3。




import secrets                              # imports secure module.

secure\_random = secrets.SystemRandom()      # creates a secure random object.

  

my\_list = \[ a , b , c , d , e \]

num\_samples = 2

  

samples = secure\_random.sample(my\_list, num\_samples)

  

print(samples)

\# \[  e ,  d \] this will have any 2 random values


19. 数字化

以下代码将一个整数转换为数字列表。




num = 123456

  

\# using map

list\_of\_digits = list(map(int, str(num)))

  

print(list\_of\_digits)

\# \[1, 2, 3, 4, 5, 6\]

  

\# using list comprehension

list\_of\_digits = \[int(x) for x in str(num)\]

  

print(list\_of\_digits)

\# \[1, 2, 3, 4, 5, 6\]


20. 检查唯一性

以下函数将检查一个列表中的所有要素是否唯一。




def unique(l):  

    if len(l)==len(set(l)):

        print("All elements are unique")

    else:

        print("List has duplicates")

  

unique(\[1,2,3,4\])

\# All elements are unique

  

unique(\[1,1,2,3\])

\# List has duplicates


- END -

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值