Iterator iterable next() item()
● 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()
Iterating over iterables: next()
In [1]: word = 'Da'
In [2]: it = iter(word)
In [3]: next(it)
Out[3]: 'D'
In [4]: next(it)
Out[4]: 'a'
In [5]: next(it)
StopIteration Traceback (most recent call last)
iter(object[, sentinel]) :iter() 函数用来生成迭代器。
参数
- object – 支持迭代的集合对象。
- sentinel – 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。
返回值:迭代器对象。
实例 st = [1, 2, 3] for i in iter(lst):
… print(i)
来自:https://blog.csdn.net/zhangshuaijun123/article/details/81901708
*和**的用法
来自:http://blog.jobbole.com/114655/
iterating over dictionaries and file connections
A
for key, value in pythonistas.items():
...:
print(key, value)
B
file = open('file.txt')
it = iter(file)
print(next(it))
This is the first line
print(next(it))
This is the second line.
Range-()返回的对象的行为好像是一个列表,但实际上不是。返回的是一个对象,它在迭代时返回所需序列的连续项,但它并没有真正列出列表,从而节省了空间。
# Create an iterator for range(3): small_value
small_value = iter(range(3))
# Print the values in small_value
print(next(small_value))
print(next(small_value))
print(next(small_value))
# Loop over range(3) and print the values
for num in range(3):
print(num)
# Create an iterator for range(10 ** 100): googol
googol = iter(range(10**100))
# Print the first 5 values from googol
print(next(googol))
print(next(googol))
print(next(googol))
print(next(googol))
print(next(googol))
利用iter()生成一个迭代器,而range()“生成了”一个可迭代的列表:
range()实际上并没有创建列表;相反,它创建一个带有迭代器的范围对象,该迭代器生成值直到达到限制
enumerate (list,start)
In [1]: avengers = ['hawkeye', 'iron man', 'thor', 'quicksilver']
In [2]: for index, value in enumerate(avengers):
....: print(index, value)
0 hawkeye
1 iron man
2 thor
3 quicksilver
In [3]: for index, value in enumerate(avengers, start=10):
....: print(index, value)
10 hakweye
11 iron man
12 thor
13 quicksilver
zip([iterable, …])
In [1]: avengers = ['hawkeye', 'iron man', 'thor', 'quicksilver']
In [2]: names = ['barton', 'stark', 'odinson', 'maximoff']
In [3]: z = zip(avengers, names)
In [4]: print(*z) ###这里用到了之前说的*的用法
('hawkeye', 'barton') ('iron man', 'stark') ('thor', 'odinson')
('quicksilver', 'maximoff')
zip()接受任意数量的iterables并返回一个zip对象,该对象是元组的迭代器。如果输出要zip对象的值,可以将其转换为列表(用list()函数),然后输出。只print一个zip对象将不会返回值,除非先将其解包。
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回元组列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
# Create a zip object from mutants and powers: z1
z1 = zip(mutants,powers)
# Print the tuples in z1 by unpacking with *
print(*z1)
# Re-create a zip object from mutants and powers: z1
z1 = zip(mutants,powers)
# 'Unzip' the tuples in z1 by unpacking with * and zip(): result1, result2
result1, result2 = zip(*z1) #### zip(*zip()) 可以unzipped
# chunks : for big data
import pandas as pd
total = 0
for chunk in pd.read_csv('data.csv', chunksize=1000):
total += sum(chunk['x'])
print(total)
# Import the pandas package
import pandas as pd
# Initialize reader object: df_reader
df_reader = pd.read_csv('ind_pop.csv', chunksize=10)
# Print two chunks
print(next(df_reader))
print(next(df_reader))
!!!生成空字典用{}
列表list[],元组tuple()、字典dictionary{},数组array([])(np),数据集set()、数列series
气死我了
List Comprehension列表生成式
[[output expression] for iterator variable in iterable]
[ output expression for iterator variable in iterable if predicate expression ].
[num ** 2 if num % 2 == 0 else 0 for num in range(10)]
# Extract the created_at column from df: tweet_time
tweet_time = df['created_at']
# Extract the clock time: tweet_clock_time
tweet_clock_time = [entry[11:19] for entry in tweet_time]
# Print the extracted times
print(tweet_clock_time)
Dictionary Comprehension
pos_neg = {num: -num for num in range(9)}
注意冒号和{}
{i : i * 2 for i in range(9)}
Generators
找到了一篇讲的非常好的内容:https://www.cnblogs.com/hump/p/6287462.html
#关于generator的生成
A
一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
L = [x * x for x in range(10)]
L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
g = (x * x for x in range(10))
g
<generator object at 0x104feab40>
创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。
我们可以直接打印出list的每一个元素,但我们怎么打印出generator的每一个元素呢?
如果要一个一个打印出来,可以通过generator的next()方法:
#B
定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:
def num_sequence(n):
"""Generate values from 0 to n."""
i = 0
while i < n:
yield i
i += 1
这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
遇到了一个身体:
Create a list comprehension to turn the list of lists into a list of dicts
# Define lists2dict()
def lists2dict(list1, list2):
"""Return a dictionary where list1 provides
the keys and list2 provides the values."""
# Zip lists: zipped_lists
zipped_lists = zip(list1, list2)
# Create a dictionary: rs_dict
rs_dict = dict(zipped_lists)
# Return the dictionary
return rs_dict
# Call lists2dict: rs_fxn
rs_fxn = lists2dict(feature_names,row_vals)
# Print rs_fxn
print(rs_fxn)
# Print the first two lists in row_lists
print(row_lists[0])
print(row_lists[1])
# Turn list of lists into list of dicts: list_of_dicts
list_of_dicts = [lists2dict(feature_names, sublist) for sublist in row_lists]
# Print the first two dictionaries in list_of_dicts
print(list_of_dicts[0])
print(list_of_dicts[1])