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

这篇具有很好参考价值的文章主要介绍了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

检查内存使用情况

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

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

4

输出某个变量的唯一ID

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

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

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

查找重复项

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

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

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

 



 文章来源地址https://www.toymoban.com/news/detail-433284.html

到了这里,关于22条最常用Python代码,快收藏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 最优字符串分隔符:零宽度空格和字符

    在文本处理和格式化中,选择合适的分隔符是至关重要的。 本文将在介绍两个不常见但功能强大的分隔符:零宽度空格和𐀀字符。 零宽度空格是Unicode字符集中的一个特殊字符,其Unicode编码为U+200B。 零宽度空格在文本中不占据任何宽度,因此是一个不可见的分隔符。 主要应

    2024年02月21日
    浏览(34)
  • Delphi中返回由空格分隔的字符串中单词的总数

    有如下一个字符串: ‘苹果 香蕉 火龙果’ 是3个词语,返回3 如果\\\"苹果 香蕉\\\"用双引号就表示是一个整体算1个词语,返回2

    2023年04月19日
    浏览(71)
  • 22个值得收藏的android开源代码-UI篇

    http://jcodecraeer.com/a/opensource/2014/1016/1791.html FloatingActionButton =============================================================================== 一个类似Android版Google+浮动功能按钮的控件,可以响应ListView的滚动事件。当列表向上滚动的时候会自动显示,向下滚动的时候自动隐藏。 [外链图片转存中…

    2024年04月15日
    浏览(36)
  • 22个值得收藏的android开源代码-UI篇(1)

    http://jcodecraeer.com/a/opensource/2014/1016/1791.html FloatingActionButton =============================================================================== 一个类似Android版Google+浮动功能按钮的控件,可以响应ListView的滚动事件。当列表向上滚动的时候会自动显示,向下滚动的时候自动隐藏。 http://jcodecraeer.co

    2024年04月10日
    浏览(29)
  • 华为OD机试 - 去除多余空格(Python)| 真题+思路+代码

    去除文本多余空格,但不去除配对单引号之间的多余空格。给出的起始和结束下标,去除多余空格后刷新的起始和结束下标。 条件约束: 不考虑起始和结束位置为空格的场景; 单词的的开始和结束下标保证涵盖一个完整的单词,即一个坐标对开始和结束

    2024年02月16日
    浏览(31)
  • appium+夜神模拟器操作微信小程序,多个模拟器要结合yaml配置文件来并发控制,一万多行代码[建议收藏]

    技术心得 python+appium+夜神模拟器+结合yaml配置文件实现并发采集任务。   代码如下 : 模拟器的配置文件如下: 欢迎大家一起学习,一起进步,喜欢私聊。

    2024年02月13日
    浏览(36)
  • seatunnel hive source 未设置分隔符导致多个字段合并成一个的问题定位解决

    seatunnel hive source 未设置分隔符导致多个字段没有切分全保存在一个字段中了,翻看源码发现分隔符是是通过delimiter设置的,只要设置这个delimiter=\\\",\\\"就可以了。 设置这个属性 delimiter=“,” 他的默认值是u0001,如果没有设置delimiter属性则会根据文件类型判断,如果是csv则使用”,”

    2024年02月16日
    浏览(37)
  • vscode markdown 使用技巧 -- 如何快速打出一个Tab 或多个空格

    背景描述:         我在使用VSCode,这玩意很好用,但是,有一个缺点是,我想使用Tab来做一些对齐,但是我发现在VSCode中,无论是Tab还是多个空格,最终显示出来的都是一个空格         使用代码可以实现打印Tab或是多个空格:`emsp;` 对应一个tab         但是我发现想要

    2024年02月06日
    浏览(49)
  • 5种Python雪花飘落代码(建议收藏)

    前言 本文章向大家介绍用 Python 实现雪花飘落效果,运行以下代码,你将会看到一个美丽的雪花效果。你可以根据自己的需求,调整代码中的参数值以及其他细节。 第一种 普通雪花代码: 第二种 随机下落的雪花: 第三种 随机颜色代码: 使用了turtle模块和random模块,会在黑

    2024年02月11日
    浏览(64)
  • 【HTML】常用实体字符(如 & nbsp; 空格)

    显示结果 描述 实体名称 实体编号 空格 nbsp; #160; 小于号 lt; #60; 大于号 gt; #62; 和号 amp; #38; \\\" 引号 quot; #34; ’ 撇号 apos; (IE不支持) #39; ¢ 分(cent) cent; #162; £ 镑(pound) pound; #163; ¥ 元(yen) yen; #165; € 欧元(euro) euro; #8364; § 小节 sect; #167; © 版权(copyright) copy; #169; ® 注

    2024年02月16日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包