python函数中的参数转为列表展示

李金龙
李金龙
管理员
505
文章
0
粉丝
Python习题评论5,585字数 123阅读模式

代码要求:

写一个函数为get_digits,要求get_digits(123456)==>[1,2,3,4,5]

 

参考代码:

  • 我写的
  1. c = []
  2. def get_digits(n):
  3.     b = str(n)
  4.     for i in range(len(b)):
  5.         c.append(int(b[i]))
  6. get_digits(123456)
  7. print(c)
  • 精简版(QQ群>>528770819)
  1. def get_digits(n):
  2.     return [int(_) for _ in str(n)]
  3. get_digits(123456)
  • 精简版2
  1. def get_digits(n):
  2.     return list(map(int,str(n)))
  3. get_digits(123456)

关于map:https://www.lijinlong.cc/python/pyxx/1833.html

  • 递归
  1. result = []
  2. def get_digits(n):
  3.         if n > 0:
  4.                 print(n)
  5.                 result.insert(0, n%10)
  6.                 get_digits(n//10)
  7. get_digits(12345)
  8. print(result)

insert():https://www.lijinlong.cc/python/pyxx/1535.html

 

 
李金龙
  • 本文由 李金龙 发表于2017年5月15日 11:42:31
  • 转载请务必保留本文链接:https://www.lijinlong.cc/python/pyxt/1878.html
匿名

发表评论

匿名网友
确定

拖动滑块以完成验证