22条最常用Python代码,快收藏

1

空格分隔多个输入

这段代码可以让你一次进行多个用空格分隔的输入,每当你要解决编程竞赛的问题时,这段代码就可以派上用场。

## Taking Two Integers as inputa,b = map(int,input().split())print("a:",a)print("b:",b)## Taking a List as inputarr = list(map(int,input().split()))print("Input List:",arr)

2

同时访问Index索引和值

enumerate()这个内置函数可以让你在or循环中同时找到索引和值。

arr = [2,4,6,3,8,10]for index,value in enumerate(arr):  print(f"At Index {index} The Value Is -> {value}")'''OutputAt Index 0 The Value Is -> 2At Index 1 The Value Is -> 4At Index 2 The Value Is -> 6At Index 3 The Value Is -> 3At Index 4 The Value Is -> 8At Index 5 The Value Is -> 10'''

3

检查内存使用情况

这段代码可以用于检查对象的内存使用情况。

4

输出某个变量的唯一ID

id()这个函数能让你找到变量的唯一id,你只需要在这个方法中传递变量名。

5

检查Anagram

一个Anagram的意思是,通过重新排列一个单词的字母,在恰好使用一次每个原始字母的情况下,组成另一个新词。

def check_anagram(first_word, second_word):  return sorted(first_word) == sorted(second_word)print(check_anagram("silent", "listen"))   # Trueprint(check_anagram("ginger", "danger"))   # False

6

合并两个字典

当你在处理数据库和JSON文件,需要将来自不同文件或表的多个数据合并到同一个文件中时,用这个代码会很方便。合并两个字典会有一些风险,比如要是出现了重复的key怎么办?还好,我们对这种情况也是有解决方案的。

basic_information = {"name":['karl','Lary'],"mobile":["0134567894","0123456789"]}academic_information = {"grade":["A","B"]}details = dict() ## Combines Dict## Dictionary Comprehension Methoddetails = {key: value for data in (basic_information, academic_information) for key,value in data.items()}print(details)## Dictionary unpackingdetails = {**basic_information ,**academic_information}print(details)## Copy and Update Methoddetails = basic_information.copy()details.update(academic_information)print(details)

7

检查一个文件是否存在

我们要确保代码中使用的文件还存在。Python使管理文件变得很容易,因为Python有读写文件的内置语法。

# Brute force Methodimport os.pathfrom os import pathdef check_for_file():         print("File exists: ",path.exists("data.txt"))if __name__=="__main__":   check_for_file()'''File exists:  False'''

8

在给定范围内,算所有数的平方

在这段代码中,我们利用内置函数itertools找到给定范围内每个整数的平方。

# METHOD 1from itertools import repeatn = 5squares = list(map(pow, range(1, n+1), repeat(2)))print(squares)# METHOD 2n = 6squares = [i**2 for i in range(1,n+1)]print(squares)"""Output  [1, 4, 9, 16, 25]"""

9

将两个list转换为dictionary

以下这个方法可以将两个列表转换为字典。

list1 = ['karl','lary','keera']list2 = [28934,28935,28936]# Method 1: zip()dictt0 = dict(zip(list1,list2))# Method 2: dictionary comprehensiondictt1 = {key:value for key,value in zip(list1,list2)}# Method 3: Using a For Loop (Not Recommended)tuples = zip(list1, list2)dictt2 = {}for key, value in tuples:  if key in dictt2:    pass  else:    dictt2[key] = valueprint(dictt0, dictt1, dictt2, sep = "\n")

10

对字符串列表进行排序

当你拿到一个学生姓名的列表,并想对所有姓名进行排序时,这段代码会非常有用。

list1 = ["Karl","Larry","Ana","Zack"]# Method 1: sort()list1.sort()# Method 2: sorted()sorted_list = sorted(list1)# Method 3: Brute Force Methodsize = len(list1)for i in range(size):  for j in range(size):    if list1[i] < list1[j]:       temp = list1[i]       list1[i] = list1[j]       list1[j] = tempprint(list1)

11

用if和Else来理解列表

当你希望根据某些条件筛选数据结构时,这段代码非常有用。

12

添加来自两个列表的元素

假设你有两个列表,并想通过添加它们的元素将它们合并到一个列表中,这段代码在这种场景中会很有用。

maths = [59, 64, 75, 86]physics = [78, 98, 56, 56]# Brute Force Methodlist1 = [  maths[0]+physics[0],  maths[1]+physics[1],  maths[2]+physics[2],  maths[3]+physics[3]]# List Comprehensionlist1 = [x + y for x,y in zip(maths,physics)]# Using Mapsimport operatorall_devices = list(map(operator.add, maths, physics))# Using Numpy Libraryimport numpy as nplist1 = np.add(maths,physics)'''Output[137 162 131 142]'''

13

对dictionary列表进行排序

当你有一个字典列表时,你可能希望借助key的帮助将它们按顺序排列起来。

dict1 = [    {"Name":"Karl",     "Age":25},     {"Name":"Lary",     "Age":39},     {"Name":"Nina",     "Age":35}]## Using sort()dict1.sort(key=lambda item: item.get("Age"))# List sorting using itemgetterfrom operator import itemgetterf = itemgetter('Name')dict1.sort(key=f)# Iterable sorted functiondict1 = sorted(dict1, key=lambda item: item.get("Age"))'''Output[{'Age': 25, 'Name': 'Karl'}, {'Age': 35, 'Name': 'Nina'}, {'Age': 39, 'Name': 'Lary'}]'''

14

计算Shell的时间

有时,了解shell或一段代码的执行时间是很重要的,这样可以用最少的时间取得更好的算法。

# METHOD 1import datetimestart = datetime.datetime.now()"""CODE"""print(datetime.datetime.now()-start)# METHOD 2import timestart_time = time.time()main()print(f"Total Time To Execute The Code is {(time.time() - start_time)}" )# METHOD 3import timeitcode = '''## Code snippet whose execution time is to be measured[2,6,3,6,7,1,5,72,1].sort()'''print(timeit.timeit(stmy = code,number = 1000))

15

检查字符串中的子字符串

我日常都会遇到的一件事,就是检查一个字符串是否包含某个子字符串。与其他编程语言不同,python为此提供了一个很好的关键字。

addresses = [  "12/45 Elm street",  '34/56 Clark street',  '56,77 maple street',  '17/45 Elm street']street = 'Elm street'for i in addresses:  if street in i:    print(i)'''output12/45 Elm street17/45 Elm street'''

16

字符串格式

代码最重要的部分是输入、逻辑和输出。在编程过程中,这三个部分都需要某种特定格式,以得到更好地、更易于阅读的输出。python提供了多种方法来改变字符串的格式。

name = "Abhay"age = 21## METHOD 1: Concatenationprint("My name is "+name+", and I am "+str(age)+ " years old.")## METHOD 2: F-strings (Python 3+)print(f"My name is {name}, and I am {age} years old")## METHOD 3: Joinprint(''.join(["My name is ", name, ", and I am ", str(age), " years old"]))## METHOD 4: modulus operatorprint("My name is %s, and I am %d years old." % (name, age))## METHOD 5: format(Python 2 and 3)print("My name is {}, and I am {} years old".format(name, age))

17

错误处理

与Java和c++一样,python也提供了try、except和finally 来处理异常错误的方法。

# Example 1try:     a = int(input("Enter a:"))        b = int(input("Enter b:"))       c = a/b     print(c)except:     print("Can't divide with zero")# Example 2try:       #this will throw an exception if the file doesn't exist.        fileptr = open("file.txt","r")   except IOError:       print("File not found")   else:       print("The file opened successfully")       fileptr.close() # Example 3try:  fptr = open("data.txt",'r')  try:    fptr.write("Hello World!")  finally:    fptr.close()    print("File Closed")except:  print("Error")

18

列表中最常见的元素

下面方法可以返回出列表中出现频率最高的元素。

19

在没有if – else的情况下计算

这段代码展示了在不使用任何if-else条件的情况下,如何简单地编写一个计算器。

import operatoraction = {  "+" : operator.add,  "-" : operator.sub,  "/" : operator.truediv,  "*" : operator.mul,  "**" : pow}print(action['*'](5, 5))    # 25

20

Chained Function调用

在python中,你可以在同一行代码调用多个函数。

def add(a,b):  return a+bdef sub(a,b):  return a-ba,b = 9,6print((sub if a > b else add)(a, b))

21

交换数值

以下是在不需要另一个额外变量的情况下交换两个数值的快速方法。

a,b = 5,7# Method 1b,a = a,b# Method 2def swap(a,b):  return b,aswap(a,b)

22

查找重复项

通过这段代码,你可以检查列表中是否有重复的值。

在这里还是要推荐下我自己建的Python学习Q群:831804576,群里都是学Python的,如果你想学或者正在学习Python ,欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),
包括我自己整理的一份2021最新的Python进阶资料和零基础教学,欢迎进阶中和对Python感兴趣的小伙伴加入!
 

 



 

  • 9
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python常用命令包括以下几个: 1. 要查看您正在运行的Python版本,可以使用以下命令: - python -? [1] - python -h [1] 2. 要查看Python版本号,可以使用以下命令: - python -V [2] - python --version [2] 3. 如果您想在不打开和编辑.py文件的情况下运行Python代码,可以使用以下命令: - python filename.py:直接运行指定的.py文件 4. 在命令行中执行Python代码时,您可能需要了解一些常用的命令: - print("Hello, World!"):打印输出文本或变量的值 - input("Enter your name: "):接收用户输入的数据 - if condition: ... else: ...:件语句,根据件执行不同的代码块 - for item in iterable: ...:循环语句,遍历可迭代对象并执行相应代码 - def function_name(parameters): ...:定义函数,用于封装可重用的代码块 - import module_name:导入外部模块,使用其中的函数和变量 - from module_name import function_name:从外部模块导入指定函数 - exit():退出Python解释器 Python是一种非常容易学习的编程语言,只要掌握了基本的语法和常用命令,就能够编写简单的程序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [全网最全的Python常见命令大全,建议收藏,以防备用](https://blog.csdn.net/SpringJavaMyBatis/article/details/127451276)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值