CS1110 - Cornell University
嚜澧S1110
Lecture 11: Iterating over Sequences
Announcements
Prelim 1
The exam is in one week. It
covers material in lecture up
through today and in lab up
through this week*s lab.
Slides by D. Gries, L. Lee, S. Marschner, W. White
Processing sequences: The map Function
General form: map(?function?, ?sequence?)
if x is a sequence of n items and
f is a function with one parameter:
which could be
a list or a string
if x is a sequence of n items and
m is a method with no parameters:
map(m, x)
map(m, x)
map(f, x)
calls the function once
for each list item
[f(x[0]), f(x[1]), #, f(x[n每1])]
[x[0].m(), x[1].m(), #, x[n每1].m()]
Mapping a function over a list
x
id1
id1
0 1.2
1 3.9
2 每4.8
3
0.1
x = [1.2, 3.9, 每4.8, 0.1]
y = map(round, x)
a function taking one argument
round(1.2)
round(3.9)
round(每4.8)
round(0.1)
>>> y
[1.0, 4.0, 每5.0, 0.0]
y
id2
id2
0 1.0
1 4.0
2 每5.0
3
0.0
Mapping a function over a list
x
id1
x = ['a', 'list', 'of', 'things']
y = map(len, x)
y
id2
id1
0
1
2
3
id2
&a*
len(&a*)
&list*
len(&list*)
&of*
len(&of*)
&things*
len(&things*)
>>> y
[1, 4, 2, 6]
0
1
2
3
1
4
2
6
Mapping a method over a list
x
id1
id1
0 &Lee*
1 &Python*
2 &CS1110*
3
&A+*
x = ['Lee', 'Python', 'CS1110', 'A+']
y = map(str.lower, x)
the method lower in the class str:
a method with no parameters*
x[0].lower()
x[1].lower()
x[2].lower()
x[3].lower()
>>> y
['lee', 'python', 'cs1110', 'a+']
y
id2
id2
0 &lee*
1 &python*
2 &cs1110*
3
&a+*
*In this case you could also
use string.lower instead,
which is the function lower
in the module string.
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- cornell university data analytics program
- cornell university data analytics certificate
- cornell university business analytics
- cornell university business
- cornell university johnson business school
- cornell university college of business
- cornell university college report
- cornell university reputation
- cornell university data analytics
- cornell university dyson business school
- cornell university johnson
- cornell university johnson school