百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

Python中的循环技术

bigegpt 2024-08-09 11:10 3 浏览

Python通过某些内置函数在各种顺序容器中支持各种循环技术。这些方法在竞争性编程中非常有用,在各种项目中也非常有用,这些项目需要使用特定技术并通过循环来维护代码的整体结构。

使用Python数据结构的不同循环技术

1.使用enumerate():enumerate()用于循环遍历容器,打印索引号以及该特定索引中的值。

# python code to demonstrate working of enumerate() 
  
for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']): 
    print(key, value) 

输出:

0 The
1 Big
2 Bang
3 Theory

2.使用zip():zip()用于组合2个类似的容器(list-list或dict-dict),依次打印值。该循环仅在较小的容器结束之前存在。zip()和enumerate()的详细说明可以在这里(https://www.geeksforgeeks.org/using-iterations-in-python-effectively/)找到。

# python code to demonstrate working of zip() 
  
# initializing list 
questions = ['name', 'colour', 'shape'] 
answers = ['apple', 'red', 'a circle'] 
  
# using zip() to combine two containers  
# and print values 
for question, answer in zip(questions, answers): 
    print('What is your {0}?  I am {1}.'.format(question, answer)) 

输出:

What is your name?  I am apple.
What is your color?  I am red.
What is your shape?  I am a circle.

3.使用iteritem():iteritems()用于遍历字典,顺序打印字典键值对。

4.使用items():items()在字典上执行的任务与iteritems()类似,但与iteritems()相比有某些缺点。

1)这非常耗时。在大型词典上调用它会消耗大量时间。

2)这会占用大量内存。 在字典上调用时,有时会占用双倍的内存。

示例1

# python code to demonstrate working of iteritems(),items() 
  
d = { "geeks" : "for", "only" : "geeks" } 
  
# using iteritems to print the dictionary key-value pair 
print ("The key value pair using iteritems is : ") 
for i,j in d.iteritems(): 
    print i,j 
      
# using items to print the dictionary key-value pair 
print ("The key value pair using items is : ") 
for i,j in d.items(): 
    print i,j 

输出:

The key value pair using iteritems is : 
geeks for
only geeks
The key value pair using items is : 
geeks for
only geeks

示例2

# python code to demonstrate working of items() 
  
king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya',  
        'Modi' : 'The Changer'} 
  
# using items to print the dictionary key-value pair 
for key, value in king.items(): 
    print(key, value) 

输出:

Akbar The Great
Modi The Changer
Chandragupta The Maurya

注意:iteritems()仅在python 2.x中有效,它已从python 3.x中删除,请使用dict.items()。

5.使用sorted():sorted()用于打印容器的排序顺序。它不会对容器进行排序,而只会按1个实例的排序顺序打印容器。可以结合使用set()来删除重复的事件。

示例1

# python code to demonstrate working of sorted() 
  
# initializing list 
lis = [ 1 , 3, 5, 6, 2, 1, 3 ] 
  
# using sorted() to print the list in sorted order 
print ("The list in sorted order is : ") 
for i in sorted(lis) : 
    print (i,end=" ") 
      
print ("\r") 
      
# using sorted() and set() to print the list in sorted order 
# use of set() removes duplicates. 
print ("The list in sorted order (without duplicates) is : ") 
for i in sorted(set(lis)) : 
    print (i,end=" ") 

输出:

The list in sorted order is : 
1 1 2 3 3 5 6 
The list in sorted order (without duplicates) is : 
1 2 3 5 6 

示例2

# python code to demonstrate working of sorted() 
  
# initializing list 
basket = ['guave', 'orange', 'apple', 'pear',  
          'guava', 'banana', 'grape'] 
  
# using sorted() and set() to print the list 
#  in sorted order 
for fruit in sorted(set(basket)): 
    print(fruit) 

输出:

apple
banana
grape
guava
guave
orange
pear

6.使用reversed():reversed()用于以相反的顺序打印容器的值。

注意:它不反映对原始列表的任何更改。

示例1

# python code to demonstrate working of reversed() 
  
# initializing list 
lis = [ 1 , 3, 5, 6, 2, 1, 3 ] 
  
  
# using revered() to print the list in reversed order 
print ("The list in reversed order is : ") 
for i in reversed(lis) : 
    print (i,end=" ") 

输出:

The list in reversed order is : 
3 1 2 6 5 3 1 

示例2

# python code to demonstrate working of reversed() 
  
# using reversed() to print in reverse order 
for i in reversed(range(1, 10, 3)): 
    print (i) 

输出:

7
4
1

与for,while循环相比,使用上述技术的优势

1)这些技术使用迅速,减少了编码工作。for,while循环需要更改容器的整个结构。

2)这些循环技术不需要对容器进行任何结构更改。它们有表示确切使用目的的关键字。然而,鉴于无法进行任何预测或猜测,for,while循环就难以理解。

3)上述循环技术使代码比在循环时使用for更为简洁。

相关推荐

【Docker 新手入门指南】第十章:Dockerfile

Dockerfile是Docker镜像构建的核心配置文件,通过预定义的指令集实现镜像的自动化构建。以下从核心概念、指令详解、最佳实践三方面展开说明,帮助你系统掌握Dockerfile的使用逻...

Windows下最简单的ESP8266_ROTS_ESP-IDF环境搭建与腾讯云SDK编译

前言其实也没啥可说的,只是我感觉ESP-IDF对新手来说很不友好,很容易踩坑,尤其是对业余DIY爱好者搭建环境非常困难,即使有官方文档,或者网上的其他文档,但是还是很容易踩坑,多研究,记住两点就行了,...

python虚拟环境迁移(python虚拟环境conda)

主机A的虚拟环境向主机B迁移。前提条件:主机A和主机B已经安装了virtualenv1.主机A操作如下虚拟环境目录:venv进入虚拟环境:sourcevenv/bin/active(1)记录虚拟环...

Python爬虫进阶教程(二):线程、协程

简介线程线程也叫轻量级进程,它是一个基本的CPU执行单元,也是程序执行过程中的最小单元,由线程ID、程序计数器、寄存器集合和堆栈共同组成。线程的引入减小了程序并发执行时的开销,提高了操作系统的并发性能...

基于网络安全的Docker逃逸(docker)

如何判断当前机器是否为Docker容器环境Metasploit中的checkcontainer模块、(判断是否为虚拟机,checkvm模块)搭配学习教程1.检查根目录下是否存在.dockerenv文...

Python编程语言被纳入浙江高考,小学生都开始学了

今年9月份开始的新学期,浙江省三到九年级信息技术课将同步替换新教材。其中,新初二将新增Python编程课程内容。新高一信息技术编程语言由VB替换为Python,大数据、人工智能、程序设计与算法按照教材...

CentOS 7下安装Python 3.10的完整过程

1.安装相应的编译工具yum-ygroupinstall"Developmenttools"yum-yinstallzlib-develbzip2-develope...

如何在Ubuntu 20.04上部署Odoo 14

Odoo是世界上最受欢迎的多合一商务软件。它提供了一系列业务应用程序,包括CRM,网站,电子商务,计费,会计,制造,仓库,项目管理,库存等等,所有这些都无缝集成在一起。Odoo可以通过几种不同的方式进...

Ubuntu 系统安装 PyTorch 全流程指南

当前环境:Ubuntu22.04,显卡为GeForceRTX3080Ti1、下载显卡驱动驱动网站:https://www.nvidia.com/en-us/drivers/根据自己的显卡型号和...

spark+python环境搭建(python 环境搭建)

最近项目需要用到spark大数据相关技术,周末有空spark环境搭起来...目标spark,python运行环境部署在linux服务器个人通过vscode开发通过远程python解释器执行代码准备...

centos7.9安装最新python-3.11.1(centos安装python环境)

centos7.9安装最新python-3.11.1centos7.9默认安装的是python-2.7.5版本,安全扫描时会有很多漏洞,比如:Python命令注入漏洞(CVE-2015-2010...

Linux系统下,五大步骤安装Python

一、下载Python包网上教程大多是通过官方地址进行下载Python的,但由于国内网络环境问题,会导致下载很慢,所以这里建议通过国内镜像进行下载例如:淘宝镜像http://npm.taobao.or...

centos7上安装python3(centos7安装python3.7.2一键脚本)

centos7上默认安装的是python2,要使用python3则需要自行下载源码编译安装。1.安装依赖yum-ygroupinstall"Developmenttools"...

利用本地数据通过微调方式训练 本地DeepSeek-R1 蒸馏模型

网络上相应的教程基本都基于LLaMA-Factory进行,本文章主要顺着相应的教程一步步实现大模型的微调和训练。训练环境:可自行定义,mac、linux或者window之类的均可以,本文以ma...

【法器篇】天啦噜,库崩了没备份(天啦噜是什么意思?)

背景数据库没有做备份,一天突然由于断电或其他原因导致无法启动了,且设置了innodb_force_recovery=6都无法启动,里面的数据怎么才能恢复出来?本例采用解析建表语句+表空间传输的方式进行...