Python练习-生成列表

1. 请利用列表生成式生成列表 [1x2, 3x4, 5x6, 7x8, …, 99x100]

提示:range(1, 100, 2) 可以生成list [1, 3, 5, 7, 9,…]

L = [x * (x + 1) for x in range(1, 100, 2)]
print L

复杂表达式

2. 在生成的表格中,对于没有及格的同学,请把分数标记为红色。

提示:红色可以用 <td style=”color:red”> 实现。

d = {'Adam': 95, 'Lisa': 85, 'Bart': 59}


def generate_tr(name, score):
    if score < 60:
        return '<tr><td>%s</td><td style="color:red">%s</td></tr>' % (name, score)
    else:
        return '<tr><td>%s</td><td>%s</td></tr>' % (name, score)


tds = [generate_tr(name, score) for name, score in d.iteritems()]
print '<table border="1">'
print '<tr><th>Name</th><th>Score</th></tr>'
print '\n'.join(tds)
print '</table>'

条件过滤

列表生成式的 for 循环后面还可以加上 if 判断。

3. 请编写一个函数,它接受一个 list,然后把list中的所有字符串变成大写后返回,非字符串元素将被忽略。

提示:
1. isinstance(x, str) 可以判断变量 x 是否是字符串;
2. 字符串的 upper() 方法可以返回大写的字母。

def toUppers(L):
    return [x.upper() for x in L if isinstance(x, str)]


print toUppers(['Hello', 'world', 101])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值