原标题:Python 必知的 20 个骚操作!

如有好文章投稿,请点击 → 这里了解详情

记住常见的 Python 技巧,可以帮助改善代码设计,减少出错,节省时间。

作者 | Chaitanya Baweja

译者 | 罗昭成,责编 | 郭芮

出品 | CSDN(ID:CSDNnews)

以下为译文:

Python 是一个解释型语言,可读性与易用性让它越来越热门。

正如 Python 之禅中所述:

优美胜于丑陋,明了胜于晦涩。

在你的日常编码中,以下技巧可以给你带来意想不到的收获。

1

字符串反转

下面的代码片段,使用 Python 中 slicing 操作,来实现字符串反转:

1# Reversing a string using slicing

2

3my_string = "ABCDE"

4reversed_string = my_string[::-1]

5

6print(reversed_string)

7

8# Output

9# EDCBA

在这篇文章(https://medium.com/swlh/how-to-reverse-a-string-in-python-66fc4bbc7379)中,你可以了解更多细节。

2

首字母大写

下面的代码片段,可以将字符串进行首字母大写,使用的是 String 类的title方法:

1my_string = "my name is chaitanya baweja"

2

3# using the title function of string class

4new_string = my_string.title

5

6print(new_string)

7

8# Output

9# My Name Is Chaitanya Baweja

3

取组成字符串的元素

下面的代码片段,可以用来找出一个字符串中所有组成他的元素,我们使用的是 set 中只能存储不重复的元素这一特性:

1my_string = "aavvccccddddeee"

2

3# converting the string to a set

4temp_set = set(my_string)

5

6# stitching set into a string using join

7new_string = ''.join(temp_set)

8

9print(new_string)

10

11# Output

12# acedv

4

重复输出String/List

可以对 String/List 进行乘法运算,这个方法,可以使用它们任意倍增。

1n = 3# number of repetitions

2my_string = "abcd"

3my_list = [1,2,3]

4

5print(my_string*n)

6# abcdabcdabcd

7

8print(my_string*n)

9# [1,2,3,1,2,3,1,2,3]

有一个很有意思的用法,定义包含n个常量的列表:

1n = 4

2my_list = [0]*n # n 表示所需列表的长度

3# [0, 0, 0, 0]

5

列表推导式

列表推导式提供了一种更优雅的方式处理列表。

以下代码片段中,将旧列表中的元素乘以2来创建新的列表:

1original_list = [1,2,3,4]

2

3new_list = [2*x forx inoriginal_list]

4

5print(new_list)

6# [2,4,6,8]

6

交换两个变量值

Python 交换两个变量的值不需要创建一个中间变量,很简单就可以实现:

1a = 1

2b = 2

3

4a, b = b, a

5

6print(a) # 2

7print(b) # 1

7

字符串拆分

使用split方法可以将一个字符串拆分成多个子串,你也可以将分割符作为参数传递进行,进行分割。

1string_1 = "My name is Chaitanya Baweja"

2string_2 = "sample/ string 2"

3

4# default separator ' '

5print(string_1.split)

6# ['My', 'name', 'is', 'Chaitanya', 'Baweja']

7

8# defining separator as '/'

9print(string_2.split('/'))

10# ['sample', ' string 2']

8

字符串拼接

join方法可以将字符串列表组合成一个字符串,下面的代码片段中,我使用,将所有的字符串拼接到一起:

1list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']

2

3# Using join with the comma separator

4print(','.join(list_of_strings))

5

6# Output

7# My,name,is,Chaitanya,Baweja

9

回文检测

在前面,我们已经说过了,如何翻转一个字符串,所以回文检测非常的简单:

1my_string = "abcba"

2

3ifmy_string == my_string[::-1]:

4print("palindrome")

5else:

6print("not palindrome")

7

8# Output

9# palindrome

10

元素重复次数

在Python中,有很多方法可以做这件事情,但是我最喜欢的还是Counter这个类。

Counter会计算每一个元素出现的次数,Counter会返回一个字典,元素作为key,出现的次数作为 value。

我们也可以使用most_common这个方法来获取出现字数最多的元素。

1fromcollections importCounter

2

3my_list = ['a','a','b','b','b','c','d','d','d','d','d']

4count = Counter(my_list) # defining a counter object

5

6print(count) # Of all elements

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

8

9print(count['b']) # of individual element

10# 3

11

12print(count.most_common(1)) # most frequent element

13# [('d', 5)]

11

变位词

使用Counter的一个很有意思的用法是找变位词:

变位词一种把某个词或句子的字母的位置(顺序)加以改换所形成的新词。

使用Counter得到的两个对象如果相等,则他们是变位词:

1fromcollections importCounter

2

3str_1, str_2, str_3 = "acbde", "abced", "abcda"

4cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)

5

6ifcnt_1 == cnt_2:

7print('1 and 2 anagram')

8ifcnt_1 == cnt_3:

9print('1 and 3 anagram')

12

try-except-else

在Python中,使用 try-except 进行异常捕获。else 可用于当没有异常发生时执行。

如果你需要执行一些代码,不管是否发生过异常,请使用 final:

1a, b = 1,0

2

3try:

4print(a/b)

5# exception raised when b is 0

6exceptZeroDivisi:

7print("division by zero")

8else:

9print("no exceptions raised")

10finally:

11print("Run this always")

13

枚举遍历

下面的代码片段中,遍历列表中的值和对应的索引:

1my_list = ['a', 'b', 'c', 'd', 'e']

2

3forindex, value inenumerate(my_list):

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

5

6# 0: a

7# 1: b

8# 2: c

9# 3: d

10# 4: e

14

对象使用内存大小

下面的代码片段展示了,如何获取一个对象所占用的内存大小:

1importsys

2

3num = 21

4

5print(sys.getsizeof(num))

6

7# In Python 2, 24

8# In Python 3, 28

15

合并两个字典

在 Python 2 中,使用update方法来合并,在 Python 3.5 中,更加简单,在下面的代码片段中,合并了两个字典,在两个字典存在交集的时候,则使用后一个进行覆盖。

1dict_1 = {'apple': 9, 'banana': 6}

2dict_2 = {'banana': 4, 'orange': 8}

3

4combined_dict = {**dict_1, **dict_2}

5

6print(combined_dict)

7# Output

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

16

代码执行时间

下面的代码片段中,使用了time这个库,来计算代码执行的时间:

1importtime

2

3start_time = time.time

4# Code to check follows

5a, b = 1,2

6c = a+ b

7# Code to check ends

8end_time = time.time

9time_taken_in_micro = (end_time- start_time)*(10**6)

10

11print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)

17

列表展开

有时候,你不知道你当前列表的嵌套深度,但是你希望把他们展开,放到一维的列表中。下面教你实现它:

1fromiteration_utilities importdeepflatten

2

3# if you only have one depth nested_list, use this

4defflatten(l):

5return[item forsublist inl foritem insublist]

6

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

8print(flatten(l))

9# [1, 2, 3, 3]

10

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

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

13

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

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

Numpy flatten 可以更好的处理你格式化好的数据。

18

随机取样

下面的例子中,使用random库,实现了从列表中随机取样。

1importrandom

2

3my_list = ['a', 'b', 'c', 'd', 'e']

4num_samples = 2

5

6samples = random.sample(my_list,num_samples)

7print(samples)

随机取样,我推荐使用secrets库来实现,更安全。下面的代码片段只能在 Python 3 中运行:

1importsecrets # imports secure module.

2secure_random = secrets.SystemRandom # creates a secure random object.

3

4my_list = ['a','b','c','d','e']

5num_samples = 2

6

7samples = secure_random.sample(my_list, num_samples)

8

9print(samples)

19

数字化

下面代码将一个整形数转成一个数字化的对象:

1num = 123456

2

3list_of_digits = list(map(int, str(num)))

4

5print(list_of_digits)

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

20

唯一性检查

下面的代码示例,可以检查列表中的元素是否是不重复的:

1defunique(l):

2iflen(l)==len(set(l)):

3print("All elements are unique")

4else:

5print("List has duplicates")

6

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

8# All elements are unique

9

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

11# List has duplicates

21

总结

这些是我在日常工作中发掘出来非常有用的代码。非常感谢阅读本文,希望对你有帮助。

原文:https://medium.com/better-programming/20-python-snippets-you-should-learn-today-8328e26ff124

本文为 CSDN 翻译,转载请注明来源出处。

责任编辑:

python separator_Python 必知的 20 个骚操作!相关推荐

  1. Python 必知的 20 个骚操作!

    以下为译文: Python 是一个解释型语言,可读性与易用性让它越来越热门. 正如 Python 之禅中所述: 优美胜于丑陋,明了胜于晦涩. 在你的日常编码中,以下技巧可以给你带来意想不到的收获. 字 ...

  2. Python小白需要知道的 20 个骚操作!​

    记住常见的 Python 技巧,可以帮助改善代码设计,减少出错,节省时间. Python 是一个解释型语言,可读性与易用性让它越来越热门.正如 Python 之禅中所述: 优美胜于丑陋,明了胜于晦涩. ...

  3. python什么时候热门_Python小白需要知道的 20 个骚操作!

    记住常见的 Python 技巧,可以帮助改善代码设计,减少出错,节省时间. Python 是一个解释型语言,可读性与易用性让它越来越热门.正如 Python 之禅中所述:优美胜于丑陋,明了胜于晦涩. ...

  4. Python 必知的20个神操作,完美诠释其简洁、优美的初衷(初学者必读)

    Python 是一个解释型语言,可读性与易用性让它越来越热门. 正如 Python 之禅中所述:优美胜于丑陋,明了胜于晦涩. 在你的日常编码中,以下技巧可以给你带来意想不到的收获: 1.字符串反转 下 ...

  5. 大多数元素python_学Python必知的20个技巧,掌握它们,准没错

    Python在设计上坚持清晰化一的风格,语法设计上更是侧重于简单.可读和优雅.Python的作者有意的设计限制性很强的语法,使得不好的编程习惯都不能通过编译.其中很重要的一项就是Python的缩进规则 ...

  6. Python 中让你相见恨晚的 20 个骚操作

    今天和大家分享 20 个 Python 编程中新手必会的"骚操作",使用的频率超高!记得点赞,收藏哦!话不多说,进入正题! 1.列表推导式 使用列表推导式创建一个列表. >& ...

  7. Python数据分析必知必会——TGI指数

    点击阅读原文,查看精彩日程! 作者 | 吹牛Z 来源 | 数据不吹牛(ID: shujubuchuiniu) 这是Python数据分析实战的第一个案例,详细解读TGI指数,并用Python代码实现基础 ...

  8. 程序员必知的20个Python技巧

    作者 | Duomly 译者 | 弯月,编辑 | 郭芮 出品 | CSDN(ID:CSDNnews) Python是一门流行且应用广泛的通用编程语言,其应用包括数据科学.机器学习.科学计算等领域,以及 ...

  9. 程序员必知的 20 个 Python 技巧!

    本文将向你展示20条非常实用的Python使用技巧. 作者 | Duomly 译者 | 弯月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python是一门流行且应用广 ...

最新文章

  1. Python(四)字符串
  2. HDU - 6992 Lawn of the Dead 线段树 + 思维
  3. Effective Java~35. 用实例域代替序数
  4. suse 安装oracle11,Suse11安装Oracle11gR2
  5. 免费查题合集大推荐,付费根本不存在的!
  6. C# WinForm开发系列
  7. sa结构组网方式_5G建网:先NSA还是SA?
  8. 大数阶乘 nyoj28
  9. linux内存泄露检查工具
  10. NOD32 病毒定义更新程序 v2.1
  11. 恒流源差分放大电路静态分析_差分放大电路分析
  12. 用cocos studio生成plist文件
  13. 【Python入门教程】第45篇 集合的并集
  14. 今年-计划写一本java方面的书籍
  15. Mathmatica 与 VS2008 链接建立问题:NETLink与MathLink
  16. hive计算指定日期所在周的第一天和最后一天
  17. 给定0-1矩阵,求连通域
  18. fatal error: cusparse.h: No such file or directory compilation terminated. error: command ‘/usr/loca
  19. 计算机程序必须在有限的步骤内完成,苏教版必修三 §1.1 算法的含义 学案.docx...
  20. Linux文本编辑工具

热门文章

  1. Java 岗大厂面试,这些必掌握(超全题目+解析),轻松拿捏~
  2. 如何灵活运用Morecoin的GMI牛熊指数?
  3. 【2022最新Java面试宝典】—— 设计模式面试题(14道含答案)
  4. Chapter6.1:线性系统的校正方法
  5. Spring Boot接入Graylog
  6. 【愚公系列】2022年09月 微信小程序-自定义导航栏功能的实现
  7. c++json库(jsoncpp)简单使用(包含下载使用方法,中文错误解决方案)
  8. Android-注册界面
  9. 在linux里复制文件命令_如何在Linux上使用“安装”命令复制文件
  10. 汽车各零部件标准对IPX9K/IP69K防水试验的要求