Python:每日一题86

2017-11-27 14:42:00
六月
来源:
http://bbs.fishc.com/thread-95274-1-1.html
转贴 766
题目:
这次很简单,希望大家踊跃参加。
一个列表,其中的元素可以是数值(整数、浮点数),也可以是字符串,要求计算各个元素之和,字符串以其长度参与计算,例如'abc',长度为3,就将3加入总和中。

  1. def sum1(list1):
  2.     ......
复制代码

  1. >>> sum1([1.2,2, 'swew23'])
  2. 9.2
  3. >>> sum1([1.2,2])
  4. 3.2
  5. >>> sum1([1,2])
  6. 3
  7. >>> sum1(['12321','asdewdew'])
  8. 13
复制代码


我的解法,供参考。


  1. def MySum(list1):
  2.     return sum([i if isinstance(i, (int, float)) else len(i) for i in list1])
复制代码
发表评论
评论通过审核后显示。