Iterators

循环的iterator,结构化输出

Iterators vs. iterables

Iterable

  • Examples: lists, strings, dictionaries, file connections

  • An object with an associated iter() method

  • Applying iter() to an iterable creates an iterator

Iterator

  • Produces next value with next()

An iterable is an object that can return an iterator, while an iterator is an object that keeps state and produces the next value when you call next() on it.

Iterating over iterables (list)

# Create a list of strings: flash
flash = ['jay garrick', 'barry allen', 'wally west', 'bart allen']

# Print each list item in flash using a for loop
for person in flash:
    print (person)


# Create an iterator for flash: superhero
superhero=iter(flash)

# Print each item from the iterator
print(next(superhero))
print(next(superhero))
print(next(superhero))
print(next(superhero))

Iterating over dictionaries

Iterating over file connections

Iterating over iterables (range)

Not all iterables are actual lists. You can use range() in a for loop as if it's a list to be iterated over:

Recall that range() doesn't actually create the list; instead, it creates a range object with an iterator that produces the values until it reaches the limit (in the example, until the value 4).

Iterators as function arguments

There are also functions that take iterators and iterables as arguments. For example, the list() and sum() functions return a list and the sum of elements, respectively.

enumerate()

enumerate() returns an enumerate object that produces a sequence of tuples, and each of the tuples is an index-value pair.

Then, we can use list to turn this enumerate object into a list of tuples and print to see what it contains

enumerate() and unpack

zip()

zip() takes any number of iterables and returns a zip object that is an iterator of tuples.

zip() and unpack

zip(*object)

use * in a call to zip() to unpack the tuples produced by zip().

* operator (splat operator)

Use iterator to load data in chunks

  1. print中使用{}, 使用.format()格式化输出 括号内可以不包含前面的字段(此时需要一一对应)

  2. index可以直接用enumerate,靠idx来call

也可以用%d的占位符,就有点C的写法...

Last updated