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

  • A+
所属分类:Python习题

代码要求:

写一个函数为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

 

李金龙

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: