Iterables include the actual sequence and the sequence of virtual computing on demand
Manual iterations: iter and next
python3.0 __next__ method provides a built-in function next, it will automatically call an object, given a
Iterables x. Call the next (x) is equivalent to the X-, the Next ()
Lists, and other objects that are not their own iterators, they can call to start the iteration iter
l = [1, 2, 3]
print (iter (l) l)
False
print(l.__next__())
AttributeError: 'list' object has no attribute 'next'
l = [1, 2, 3]
i = iter(l)
print(next(i))
1
print(i.__next__())
2
l = [1, 2, 3]
for x in l:
print(x**2, end=' ')
1 4 9
l = [1, 2, 3]
i = iter(l)
while True:
try:
j = next(i)
except StopIteration:
break
else:
print(j ** 2, end=' ')
1 4 9
python2 iterative method is x.next, python3 is x .__ next__, but indeed the next function are available.
Other iterators
d = {'a':1, 'b':2, 'c':3}
for k in d.keys():
print(k, d[k])
a 1
b 2
c 3
python3 in, it has a dictionary iterator
i = iter(d)
print(next(i))
print(next(i))
print(next(i))
a
b
c
So we do not need to call the keys method to traverse the dictionary, for the iterative protocol to obtain keys.
for k in d:
print(k, d[k])
a 1
b 2
c 3
shelves and os.popen results will also be iterative
import os
p = os.popen('dir')
print(p.__next__())
F is the drive roll has no label.
Note py2 the popen object supports p.next method, py3 support p .__ next __ () method.
Iteration agreement also needs to be packaged to result in a list to see the value. The first iteration may object to return a
A result, instead of a list
a = range(5)
print(a)
range(0, 5)
i = iter(a)
print(next(i))
print(next(i))
0
1
print(list(range(5)))
[0, 1, 2, 3, 4]
List comprehension
l = []
for i in [1, 2, 3]:
l.append(i+1)
print(l)
[2, 3, 4]
Compared to a normal cycle, list comprehension can also achieve the same purpose, and more concise than the speed
General circulation faster
print([i+1 for i in [1, 2, 3]])
[2, 3, 4]
List comprehension file
with open('some.py', 'w') as f:
f.write('import os\n')
f.write('a = 1\n')
f.write('b = 2\n')
with open('some.py') as f:
print(f.read())
import os
a = 1
b = 2
f = open('some.py')
line = f.readlines()
print(line)
['import os\n', 'a = 1\n', 'b = 2\n']
If you want to remove the line break at the end of the line then.
print([l.rstrip() for l in line])
['import os', 'a = 1', 'b = 2']
Because the list comprehension like a for loop is an iterative environment, we do not even have to open the file in advance.
l = [line.rstrip() for line in open('some.py')]
print(l)
['import os', 'a = 1', 'b = 2']
In addition. List comprehension performance is also very strong, we can run on a file at any iteration of
String Manipulation
print([line.upper() for line in open('some.py')])
['IMPORT OS\n', 'A = 1\n', 'B = 2\n']
List comprehensions can also be nested for loops and if
lines = [line.rstrip() for line in open('some.py') if line[0] == 'a']
print(lines)
['a = 1']
print([x+y for x in 'abc' for y in 'lmn'])
[ 'Al', 'the', 'of', 'BL', 'bm', 'bn', 'table', 'cm', 'cn']
List comprehension, in members of the test, map built-in functions, sorted and zip uses an iterative protocol
When the application file, it will automatically scan
upper = [line.upper() for line in open('some.py')]
print(upper)
['IMPORT OS\n', 'A = 1\n', 'B = 2\n']
print(list(map(str.upper, open('some.py'))))
['IMPORT OS\n', 'A = 1\n', 'B = 2\n']
print('a = 1\n' in open('some.py'))
True
print(sorted(open('some.py')))
['a = 1\n', 'b = 2\n', 'import os\n']
print(list(zip(open('some.py'), open('some.py'))))
[('import os\n', 'import os\n'), ('a = 1\n', 'a = 1\n'), ('b = 2\n', 'b = 2\n')]
print(list(enumerate(open('some.py'))))
[(0, 'import os\n'), (1, 'a = 1\n'), (2, 'b = 2\n')]
print(list(filter(bool, open('some.py'))))
['import os\n', 'a = 1\n', 'b = 2\n']
import functools, operator
print(functools.reduce(operator.add, open('some.py')))
import os
a = 1
b = 2
print(sum([1, 2, 3, 4, 5]))
15
print(any(['spam', '', 'mi']))
True
print(all(['spam', '', 'mi']))
False
print(max([1, 2, 3, 4, 5]))
5
print (min ([1, 2, 3, 4, 5]))
1
max and min may be applied to the file
print(max(open('some.py')))
import os
print(min(open('some.py')))
a = 1
Iteration protocol may also act directly on the file
print(list(open('some.py')))
['import os\n', 'a = 1\n', 'b = 2\n']
print(tuple(open('some.py')))
('import os\n', 'a = 1\n', 'b = 2\n')
print('&&'.join(open('some.py')))# (牛逼)
import os
&&a = 1
&&b = 2
a, *b = open('some.py')
print(a)
print(b)
import os
['a = 1\n', 'b = 2\n']
Analytic and collection
print(set(open('some.py')))
{'b = 2\n', 'a = 1\n', 'import os\n'}
print({line for line in open('some.py')})
{'a = 1\n', 'b = 2\n', 'import os\n'}
print({ix: line for ix, line in enumerate(open('some.py'))})
{0: 'import os\n', 1: 'a = 1\n', 2: 'b = 2\n'}
print({line for line in open('some.py') if line[0] == 'a'})
{'a = 1\n'}
print({ix: line for ix, line in enumerate(open('some.py')) if line[0] == 'a'})
{1: 'a = 1\n'}
def f(a, b, c):
print(a, b, c, sep = '&')
f(1, 2, 3)
1-2-3
f(*open('some.py'))
import os
&a = 1
&b = 2
x , y = (1, 2), (3, 4)
print(list(zip(x, y)))
[(1, 3), (2, 4)]
a, b = zip(*zip(x, y))
print(a)
print(b)
(1, 2)
(3, 4)
Different range and other iterators, rang it was not his own iterator, and he supports multiple iterators on results
They will remember their place
r = range(3)
i1 = iter(r)
print(next(i1))
0
print(next(i1))
1
i2 = iter(r)
print(next(i2))
0
print(next(i1))
2
The zip, map, filter does not support the active iterators on the same results
z = zip((1, 2, 3), (10, 11, 12))
i1 = iter(z)
i2 = iter(z)
print(next(i1))
(1, 10)
print(next(i1))
(2, 11)
print(next(i2))
(3, 12)
m = map(abs,(-1, 0, 1))
i1 = iter(m)
i2 = iter(m)
print(next(i1)) # 1
print(next(i1)) # 0
print(next(i1)) # 1
print(next(i2)) # StopIteration
r = range(3)
r1, r2 = iter(r), iter(r)
print(next(r1)) # 0
print(next(r1)) # 1
print(next(r1)) # 2
print(next(r2)) # 0
It returns a new object by supporting multiple iterations iter, a single iteration returns itself.
py3 in the dictionary because the keys are not returned a list, so it should be first of all to show him with a list
Or use the sorted
d = {'a':1, 'b':2, 'c':3}
for k in sorted(d.keys()):
print(k, d[k], end=' ')
a 1 b 2 c 3
for k in sorted(d):
print(k, d[k], end = ' ')