第4关:迭代器

编程要求:

本关的编程任务是补全ListCalculate.py文件中的部分代码,具体要求如下:

  • 当输入一个列表时,填入将列表List转换为迭代器的代码;

  • 填入用next()函数遍历迭代器IterList的代码。

本关涉及的代码文件ListCalculate.py的代码框架如下:

  1. List = []
  2. member = input()
  3. for i in member.split(','):
  4. result = i
  5. List.append(result)
  6. # 请在此添加代码,将List转换为迭代器的代码
  7. ########## Begin ##########
  8. ########## End ##########
  9. while True:
  10. try:
  11. # 请在此添加代码,用next()函数遍历IterList的代码
  12. ########## Begin ##########
  13. ########## End ##########
  14. result = int(num) * 2
  15. print(result)
  16. except StopIteration:
  17. break

测试说明:

本文的测试文件是ListCalculate.py,具体测试过程如下:

  1. 平台自动编译生成ListCalculate.exe

  2. 平台运行ListCalculate.exe,并以标准输入方式提供测试输入;

  3. 平台获取ListCalculate.exe输出,并将其输出与预期输出对比。如果一致则测试通过,否则测试失败。

以下是平台对src/step4/ListCalculate.py的样例测试集: 预期输入:

  1. 5,6,7,8,9

预期输出:

  1. 10
  2. 12
  3. 14
  4. 16
  5. 18

 答案:

List = []
member = input()
for i in member.split(','):
    result = i
    List.append(result)
#请在此添加代码,将List转换为迭代器的代码
#********** Begin *********#
IterList = iter(List)
#********** End **********#
while True:
    try:
	    #请在此添加代码,用next()函数遍历IterList的代码
        #********** Begin *********#
        num = next(IterList)
        #********** End **********#
        result = int(num) * 2
        print(result)
    except StopIteration:
        break
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值