python iteration

高洛峰
高洛峰Original
2016-11-19 16:27:221376browse

In python, we can iterate over list, tuple, dict or other iterable objects to traverse and extract each element.

How to determine whether an object is an iterable object

To determine whether an object is an iterable object, you can use isinstance to determine whether it is an Iterable type of the collections module.
For example:

from collections import Iterable

isinstance('hello world',Iterable) # True
isinstance([1,2,3,4],Iterable) #True
isinstance(231,Iterable) #False

List tuple string When looping

fruits = ['apple','banana','peal','water melon']
for fruit in fruits:
    print fruit

while iterating, I want to get the subscript while getting the value. What should I do?
We can use the built-in enumerate() function in python to assemble list, tuple, string, etc. into an indexed enumerate object.

for index,fruit in enumerate(fruits):
    print index,fruit

Dict iteration

Dict dictionary itself has key and value.

When using for...in... iteration, the default is key iteration.

Dict 迭代
Dict字典本身带有key和value。
利用for...in...迭代的时候,默认是key迭代。

The output result will be:

banana
apple
peal

So what if it is a value iteration?

We can use the itervalues ​​function of the dictionary itself.

for value in d.itervalues():
    print value

We want both key and value during iteration, what should we do?

for key,value in d.iteritems():
    print key,value


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:python list generatorNext article:python list generator