HeadFirstPython 学习笔记(0)--list comprehension(列表推导)

clean_james = []
clean_sarah = []
clean_julie = []
clean_mikey = []
for each_time in james:
    clean_james.append(sanitize(each_time))
for each_time in sarah:
    clean_sarah.append(sanitize(each_time))
for each_time in julie:
    clean_julie.append(sanitize(each_time))
for each_time in mikey:
    clean_mikey.append(sanitize(each_time))  
    
#使用代码推导,可以替换为:

clean_james = [sanitize(each_time) for each_time in james]
clean_sarah = [sanitize(each_time) for each_time in sarah]
clean_julie = [sanitize(each_time) for each_time in julie]
clean_mikey = [sanitize(each_time) for each_time in mikey]

#其它例子:

Start by transforming a list of minutes into a list of seconds:
>>> mins = [1, 2, 3]
>>> secs = [m * 60 for m in mins]
>>> secs
[60, 120, 180]
How about meters into feet?
>>> meters = [1, 10, 3]
>>> feet = [m * 3.281 for m in meters]
>>> feet
[3.281, 32.81, 9.843]
Given a list of strings in mixed and lowercase, it’s a breeze to transform the strings to UPPERCASE:
>>> lower = ["I", "don't", "like", "spam"]
>>> upper = [s.upper() for s in lower]
>>> upper
['I', "DON'T", 'LIKE', 'SPAM']
Let’s use your sanitize() function to transform some list data into correctly formatted times:
>>> dirty = ['2-22', '2:22', '2.22']
>>> clean = [sanitize(t) for t in dirty]
>>> clean
['2.22', '2.22', '2.22']
It’s also possible to assign the results of the list transformation back onto the original target identifier. This
example transforms a list of strings into floating point numbers, and then replaces the original list data:
>>> clean = [float(s) for s in clean]
>>> clean
[2.22, 2.22, 2.22]
And, of course, the transformation can be a function chain, if that’s what you need:
>>> clean = [float(sanitize(t)) for t in ['2-22', '3:33', '4.44']]
>>> clean
[2.22, 3.33, 4.44]


你可能感兴趣的:(python,comprehension,list.)