Home > Backend Development > Python Tutorial > python iteration

python iteration

高洛峰
Release: 2016-11-19 16:27:22
Original
1407 people have browsed it

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
Copy after login

List tuple string When looping

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

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
Copy after login

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迭代。
Copy after login

The output result will be:

banana
apple
peal
Copy after login

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
Copy after login

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

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template