python代码解释大全总结表(Python常用代码有哪些?)(python程序代码及解释说明)

网友投稿 1519 2022-08-04

python代码解释大全总结表(Python常用代码有哪些?)(python程序代码及解释说明)

python代码解释大全总结表(Python常用代码有哪些?)(python程序代码及解释说明)

Python因其上手快,语言简洁,非常适用初学者,并且Python拥有很多第三方库,使用相当方便,很多情况,直接调用第三方库就可以解决。但是仍然有很多初学者疑问,那那么多的代码与语句,记不住怎么办?今天,就来和大家分享一下关于Python常用的一些代码,希望对大家有所帮助。

1.反转字符串

ABCDE --> EDCBA

# Reversing a string using slicing my_string = "ABCDE" reversed_string = my_string[::-1]

print(reversed_string) # Output # EDCBA

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

可以将字符串的首字母大写

my_string = "my name is chaitanya baweja" new_string = my_string.title()

print(new_string) # My Name Is Chaitanya Baweja

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

去掉字符串中的重复字符

my_string = "aavvccccddddeee" temp_set = set(my_string)

new_string = .join(temp_set)

print(new_string)

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

直接使用*相乘

n = 3 my_string = "abcd" my_list = [1,2,3] print(my_string*n) print(my_list*n) import streamlit as st

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

n = 4 my_list = [0]*n # [0, 0, 0, 0]

5. 列表解析

对列表的每个元素进行操作

original_list = [1,2,3,4] new_list = [2*x for x in original_list] print(new_list) # [2,4,6,8]

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

直接交换变量的值

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" print(string_1.split()) # [ My , name , is , Chaitanya , Baweja ] print(string_2.split( / ))

# [ sample , string 2 ]

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

列表元素合并

list_of_strings = [ My , name , is , Chaitanya , Baweja ] print( , .join(list_of_strings)) # Output # My,name,is,Chaitanya,Baweja

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

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

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

10. 列表的要素频率

列表元素计数,获取最常出现的元素

from collections import Counter

my_list = [ a , a , b , b , b , c , d , d , d , d , d ] count = Counter(my_list) print(count)

# Counter({ d : 5, b : 3, a : 2, c : 1}) print(count[ b ])

# 3 print(count.most_common(1))

# [( d , 5)]

11. 查找两个字符串是否为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块

a, b = 1,0 try:

print(a/b) 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. 合并两个字典

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()

a, b = 1,2 c = a+ b

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

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]

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 ]

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

以下代码仅限用于Python 3。

import secrets secure_random = secrets.SystemRandom() my_list = [ a , b , c , d , e ] num_samples = 2 samples = secure_random.sample(my_list, num_samples) print(samples) # [ e , d ]

19. 数字化

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

num = 123456 list_of_digits = list(map(int, str(num))) print(list_of_digits) # [1, 2, 3, 4, 5, 6] 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])

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:初学者学习c语言需要会什么?(零基础学C语言要学习哪些内容)(c语言入门后学什么)
下一篇:python用来干什么?为什么这么多人追捧(为什么要用python)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~