Python常用技巧有哪些

其他教程   发布日期:2024年12月17日   浏览次数:205

本文小编为大家详细介绍“Python常用技巧有哪些”,内容详细,步骤清晰,细节处理妥当,希望这篇“Python常用技巧有哪些”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1.字符串反转

使用Python切片反转字符串:

  1. # Reversing a string using slicing
  2. my_string = "ABCDE"
  3. reversed_string = my_string[::-1]
  4. print(reversed_string)
  5. # Output
  6. # EDCBA

2.每个单词的第一个字母大写

使用title函数方法:

  1. my_string = "my name is chaitanya baweja"
  2. # using the title() function of string class
  3. new_string = my_string.title()
  4. print(new_string)
  5. # Output
  6. # My Name Is Chaitanya Baweja

3. 字符串查找唯一元素

使用集合的概念查找字符串的唯一元素:

  1. my_string = "aavvccccddddeee"
  2. # converting the string to a set
  3. temp_set = set(my_string)
  4. # stitching set into a string using join
  5. new_string = ''.join(temp_set)
  6. print(new_string)
  7. # output
  8. # cdvae

4.重复打印字符串和列表n次

你可以使用乘法符号(*)打印字符串或列表多次:

  1. n = 3 # number of repetitions
  2. my_string = "abcd"
  3. my_list = [1,2,3]
  4. print(my_string*n)
  5. # abcdabcdabcd
  6. print(my_list*n)
  7. # [1,2,3,1,2,3,1,2,3]

5.列表生成

  1. # Multiplying each element in a list by 2
  2. original_list = [1,2,3,4]
  3. new_list = [2*x for x in original_list]
  4. print(new_list)
  5. # [2,4,6,8]

6.变量交换

  1. a = 1
  2. b = 2
  3. a, b = b, a
  4. print(a) # 2
  5. print(b) # 1

7.字符串拆分为子字符串列表

使用.split()函数:

  1. string_1 = "My name is Chaitanya Baweja"
  2. string_2 = "sample/ string 2"
  3. # default separator ' '
  4. print(string_1.split())
  5. # ['My', 'name', 'is', 'Chaitanya', 'Baweja']
  6. # defining separator as '/'
  7. print(string_2.split('/'))
  8. # ['sample', ' string 2']

8.多个字符串组合为一个字符串

  1. list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
  2. # Using join with the comma separator
  3. print(','.join(list_of_strings))
  4. # Output
  5. # My,name,is,Chaitanya,Baweja

9.检测字符串是否为回文

  1. my_string = "abcba"
  2. if my_string == my_string[::-1]:
  3. print("palindrome")
  4. else:
  5. print("not palindrome")
  6. # Output
  7. # palindrome

10. 统计列表中元素的次数

  1. # finding frequency of each element in a list
  2. from collections import Counter
  3. my_list = ['a','a','b','b','b','c','d','d','d','d','d']
  4. count = Counter(my_list) # defining a counter object
  5. print(count) # Of all elements
  6. # Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
  7. print(count['b']) # of individual element
  8. # 3
  9. print(count.most_common(1)) # most frequent element
  10. # [('d', 5)]

11.判断两个字符串是否为Anagrams

Anagrams的含义为两个单词中,每个英文单词(不含大小写)出现的次数相同,使用Counter类判断两个字符串是否为Anagrams。

  1. from collections import Counter
  2. str_1, str_2, str_3 = "acbde", "abced", "abcda"
  3. cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
  4. if cnt_1 == cnt_2:
  5. print('1 and 2 anagram')
  6. if cnt_1 == cnt_3:
  7. print('1 and 3 anagram')
  8. # output
  9. # 1 and 2 anagram

12. 使用try-except-else-block模块

except获取异常处理:

  1. a, b = 1,0
  2. try:
  3. print(a/b)
  4. # exception raised when b is 0
  5. except ZeroDivisionError:
  6. print("division by zero")
  7. else:
  8. print("no exceptions raised")
  9. finally:
  10. print("Run this always")
  11. # output
  12. # division by zero
  13. # Run this always

13. 使用枚举函数得到key/value对

  1. my_list = ['a', 'b', 'c', 'd', 'e']
  2. for index, value in enumerate(my_list):
  3. print('{0}: {1}'.format(index, value))
  4. # 0: a
  5. # 1: b
  6. # 2: c
  7. # 3: d
  8. # 4: e

14.检查对象的内存使用情况

  1. import sys
  2. num = 21
  3. print(sys.getsizeof(num))
  4. # In Python 2, 24
  5. # In Python 3, 28

15.合并字典

  1. dict_1 = {'apple': 9, 'banana': 6}
  2. dict_2 = {'banana': 4, 'orange': 8}
  3. combined_dict = {**dict_1, **dict_2}
  4. print(combined_dict)
  5. # Output
  6. # {'apple': 9, 'banana': 4, 'orange': 8}

16.计算执行一段代码所花费的时间

使用time类计算运行一段代码所花费的时间:

  1. import time
  2. start_time = time.time()
  3. # Code to check follows
  4. for i in range(10**5):
  5. a, b = 1,2
  6. c = a+ b
  7. # Code to check ends
  8. end_time = time.time()
  9. time_taken_in_micro = (end_time- start_time)*(10**6)
  10. print(time_taken_in_micro)
  11. # output
  12. # 18770.217895507812

17. 列表展开

  1. from iteration_utilities import deepflatten
  2. # if you only have one depth nested_list, use this
  3. def flatten(l):
  4. return [item for sublist in l for item in sublist]
  5. l = [[1,2,3],[3]]
  6. print(flatten(l))
  7. # [1, 2, 3, 3]
  8. # if you don't know how deep the list is nested
  9. l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
  10. print(list(deepflatten(l, depth=3)))
  11. # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

18. 列表采样

  1. import random
  2. my_list = ['a', 'b', 'c', 'd', 'e']
  3. num_samples = 2
  4. samples = random.sample(my_list,num_samples)
  5. print(samples)
  6. # [ 'a', 'e'] this will have any 2 random values

19.数字化

将整数转化成数字列表:

  1. num = 123456
  2. # using map
  3. list_of_digits = list(map(int, str(num)))
  4. print(list_of_digits)
  5. # [1, 2, 3, 4, 5, 6]
  6. # using list comprehension
  7. list_of_digits = [int(x) for x in str(num)]
  8. print(list_of_digits)
  9. # [1, 2, 3, 4, 5, 6]

20.检查列表元素的唯一性

检查列表中每个元素是否为唯一的:

  1. def unique(l):
  2. if len(l)==len(set(l)):
  3. print("All elements are unique")
  4. else:
  5. print("List has duplicates")
  6. unique([1,2,3,4])
  7. # All elements are unique
  8. unique([1,1,2,3])
  9. # List has duplicates

以上就是Python常用技巧有哪些的详细内容,更多关于Python常用技巧有哪些的资料请关注九品源码其它相关文章!