首页 > 编程知识 正文

python快速编程入门黑马答案(用python编三天打鱼两天晒网)

时间:2023-05-06 08:21:52 阅读:84682 作者:472

作者

翻译人员|火源、编辑责任| Carol

展出|程序人生(ID:coder_life ) )

Python是一种no-BS编程语言。 可读性和设计简单是受欢迎的两个最大原因。

正如Python禅宗所说:

比丑还美。

总比不易理解好。

因此,记住常见的Python技术可以改善代码设计。 这样可以为你节省很多时间,省去每次上Stack Overflow找答案的麻烦。

在你的日常编码练习中,以下技巧很有用。

1 .反转字符串

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

# # reversingastringusingslicingmy _ stringmy=' abcde ' reversed _ string=my _ string [ :3360-1 ]打印(reversed ((,

359媒体.com/swlh/how-to-reverse-a-string-in-python-66fc4BBC 7379

2 .使用标题的大小写(首字母大写) ) ) ) ) ) ) ) ) ) ) ) )。

以下代码段可以用于将字符串的第一个字符大写。 使用字符串类的title方法进行。

my _ string=' mynameischaitanyabaweja ' # usingthetitlefunctionofstringclassnew _ string=my _ string.title print (新

可以使用以下代码段来搜索字符串中的所有唯一元素。 可以使用集合中所有元素都是唯一的属性。

my _ string=' aavvcccdddeee ' # convertingthestringtoasettemp _ set=set (my _ string ) ) stitchingsetintoastringusing

可以乘以字符串或列表。 现在,可以以任意倍数增加它们。

n=3# numberofrepetitionsmy _ string=' ABCD ' my _ list=[ 1,2,3 ]打印(my _ string * n ) abcdabcdprint ()

n=4my _ list=[0] * n # Ndenotesthelengthoftherequiredlist # [ 0,0,0 ]5.列表推导公式

列表推导公式为基于其他列表之上创建列表提供了良好的方法。

以下代码段用旧列表中的每个元素乘以2来创建新列表。

# # multiplyingeachelementinalistby2original _ list=[ 1,2,3,4 ]新建_ list=[2*氧化物_ list ]打印(

359 medium.com/swlh/list-comprehension s-in-python-e8d 409 bb 216 e

6 .两个变量交换值

使用Python,在两个变量之间交换值变得非常容易,而无需使用其他变量。

a=1b=2a,b=b,a打印(a ) # 2打印(b ) b ) # 17 .将字符串分割为部分字符串列表

可以使用字符串类的. split方法将字符串拆分为子字符串列表。 也可以将分割的分隔符作为参数传递。

string _1=' mynameischaitanyabaweja ' string _2=' sample/string2' #默认分隔符' '打印(string _1. sp lint

join方法将作为参数传递的字符串列表组合成一个字符串。 本示例使用逗号分隔符号将它们分离。

list _ of _ strings=“我的”,“名称”,“柴坦雅”,“贝爷”#

Using join with the comma separatorprint(','.join(list_of_strings))# Output# My,name,is,Chaitanya,Baweja

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

因为我们已经讨论过如何反转字符串,所以回文就变的小菜一碟了。

my_string = "abcba"if my_string == my_string[::-1]: print("palindrome")else: print("not palindrome")# Output# palindrome

10.列表中元素的频次

有很多种方法都可以做到这一点,但我最喜欢的是用Python Counter类。

Python Counter能够追踪容器中每个元素的频率。Counter返回字典,其中元素作为键、频率作为值。

我们还会使用most_common函数来获取列表中most_frequent element。

# finding frequency of each element in a listfrom collections import Countermy_list = ['a','a','b','b','b','c','d','d','d','d','d']count = Counter(my_list) # defining a counter objectprint(count) # Of all elements# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})print(count['b']) # of individual element# 3print(count.most_common(1)) # most frequent element# [('d', 5)]

11.找出两个字符串是否为字谜(Anagrams)

Counter 类的一个十分有趣的应用就是查找字谜。字谜是通过重新排列不同单词或短语的字母而形成的单词或短语。如果两个字符串的Counter 对象相等,那么它们就互为字谜。

from collections import Counterstr_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处理错误

Python中的错误处理可以使用try/except轻松完成。向这个语句中添加一个else语句可能会十分有用,它将在try部分没有引发异常时运行。

如果你需要运行某些程序,而无需考虑异常,那么请使用finally。

a, b = 1,0try: print(a/b) # exception raised when b is 0except ZeroDivisionError: print("division by zero")else: print("no exceptions raised")finally: print("Run this always")

13.使用Enumerate来获取索键值对

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

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.检查对象的内存使用情况

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

更多信息:

https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609

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

15.合并两个字典

在Python 2中,我们使用update方法来合并两个字典,Python 3.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 timestart_time = time.time# Code to check followsa, b = 1,2c = a+ b# Code to check endsend_time = time.timetime_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 thisdef 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 nestedl = [[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 flatten会是一种很好的方法。

Numpy flatten:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.htmlhttps:/docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html

18.从列表中采样

以下的代码段使用random库从给定列表中随机生成n个样本。

import randommy_list = ['a', 'b', 'c', 'd', 'e']num_samples = 2samples = 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 = 2samples = secure_random.sample(my_list, num_samples)print(samples)# [ 'e', 'd'] this will have any 2 random values

Secrets:

https://docs.python.org/3/library/secrets.html

19.数字化

以下代码段将会把整数转换为数字列表。

num = 123456list_of_digits = list(map(int, 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 uniqueunique([1,1,2,3])# List has duplicates

这些都仅仅是我在自己日常工作中发现的非常有用的小代码段,感谢你的阅读,希望能帮到你。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。