python数字⼤⼩写转换代码_【经验分享】20个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 classnew_string = my_string.title()
print(new_string) # Output# My Name Is Chaitanya Baweja
3、查字符串的唯⼀要素
以下代码可⽤于查字符串中所有的唯⼀要素。我们使⽤其属性,其中⼀套字符串中的所有要素都是唯⼀的。
my_string = "aavvccccddddeee"
# converting the string to a settemp_set = set(my_string) # stitching set into a string using joinnew_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 = 4my_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) # 2print(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 separatorprint(','.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 listfrom 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
st_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 0except 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
sizeof(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 followsa, b = 1,2c = a+ b# Code to check endsend_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 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扁平化是更佳选择。
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 maplist_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
成长离不开与优秀的伙伴共同学习,如果你需要好的学习环境,好的学习资源,项⽬教程,零基础学习,这⾥欢迎每⼀位热爱Python的⼩伙伴,点击:Python学习圈

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。