Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

>>>

>>> knights = {‘gallahad‘: ‘the pure‘, ‘robin‘: ‘the brave‘}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>>

>>> for i, v in enumerate([‘tic‘, ‘tac‘, ‘toe‘]):
...     print(i, v)
...
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>>

>>> questions = [‘name‘, ‘quest‘, ‘favorite color‘]
>>> answers = [‘lancelot‘, ‘the holy grail‘, ‘blue‘]
>>> for q, a in zip(questions, answers):
...     print(‘What is your {0}?  It is {1}.‘.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>>

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>>

>>> basket = [‘apple‘, ‘orange‘, ‘apple‘, ‘pear‘, ‘orange‘, ‘banana‘]
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>>

>>> words = [‘cat‘, ‘window‘, ‘defenestrate‘]
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
[‘defenestrate‘, ‘cat‘, ‘window‘, ‘defenestrate‘]
时间: 2024-10-11 18:11:42

Looping Techniques的相关文章

Python -- 循环技巧(Looping Techniques)

1.当想同时得到索引和对应的值时,可以用enumerate()函数 for i, v in enumerate(['tic', 'tac', 'toe']): print i, v 0 tic 1 tac 2 toe 2.要同时循环两个或多个序列,可以与zip()函数配对. questions = ['name', 'quest', 'favorite color'] answers = ['lancelot', 'the holy grail', 'blue'] for q, a in zip

Python数据结构(二)

5.2. The del statement There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or

Python Tutorial 学习(五)--Data Structures

5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它可不仅仅只有那么一点点,这里给出一个更详细一点的说明.来吧骚连,打开你的命令行窗口 >>>help(list) 看看会出来一些什么~~` list.append(x) 向一个序列里面追加元素 x a = [] a.append(x) # 假设x已经定义了 a[len(a):] = [x] l

Python 2.7.8 学习笔记(001)python manuals/the python tutorial

从今天开始学python, python有点意思,第一感觉界面和matlab有点像. 手头没有什么资料,就从安装好了的一个python 2.7.8,里面有个英文版的manual,那就只好从这里开始吧,为什么不是中文版的呢??那就边看边翻译吧. python漫游指南:python是一种简单易学功能强大的编程语言.它有高效的数据结构和简单但有效的面向对象编程方法.python优雅的语法和动态拼写以及解释特性,使得它在许多平台上成为一种理想的脚本语言和快速程序开发工具. python的解释器和扩展标准

python学习(3)- 深入流程控制

if 語句 也许最有名的语句类型是 if 语句.例如 x = int(input("Please enter an integer: ")) Please enter an integer: 42 if x < 0: - x = 0 - print('Negative changed to zero') - elif x == 0: - print('Zero') - elif x == 1: - print('Single') - else: - print('More') -

Python更多控制流工具(一)

4.1. if Statements Perhaps the most well-known statement type is the if statement. For example: if语句可能是最常见的控制流语句了,例如: >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... pr

Looping and dictionaries

If you use a dictionary in a for statement, it traverses the keys of the dictionary. For example, print_hist prints each key and the corresponding value: Print dictionary in alphabetical order: Reverse lookup Given a dictionary d and a key k, it is e

(paper reading)Entity Linking with a Knowledge Base: Issues, Techniques, and Solutions

给定一个包含一系列实体E的知识库,以及提到了M个已确定实体的文本集合,实体链接的目的是将文本中提到的每个实体m∈M链接到知识库中对应的实体e∈E上.如果文本中提到的实体在知识库中没有对应,则被称为unlinkable mentions,对这样的一类实体,一个实体链接系统会给它加上一个特殊的标签NIL. 一个典型的实体链接系统应该包含三个模块: Candidate entity generation 对M当中的每一个m,实体链接系统需要在知识库中找出候选的实体集合Em,主要的实现方法有: dict

Java Performance Optimization Tools and Techniques for Turbocharged Apps--reference

Java Performance Optimization by: Pierre-Hugues Charbonneau reference:http://refcardz.dzone.com/refcardz/java-performance-optimization Java is among the most widely used programming languages in the software development world today. Java applications