Skip to content

Instantly share code, notes, and snippets.

@ipconfiger
Last active September 6, 2017 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipconfiger/8376ee9b5f0eb4f3cef3e687f8d331f7 to your computer and use it in GitHub Desktop.
Save ipconfiger/8376ee9b5f0eb4f3cef3e687f8d331f7 to your computer and use it in GitHub Desktop.
一行代码转换数字字符串到大写, 比如 104 =>壹佰零肆
终极方法
lambda number_string: (lambda seq: "".join(reversed(["".join(["".join([p, ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"][int(n)], u]) for p, n, u in reversed(s[0])]) + s[1] for s in [(lambda sub_seq: [[["零", tp[0], tp[1]] if i<(len(sub_seq)-1) and int(sub_seq[i+1])< 1 else ["", tp[0], tp[1]] for i, tp in enumerate(zip(sub_seq, ["", "拾", "佰", "仟"])) if int(tp[0])], unit])(seq[idx*4:(idx+1)*4] or []) for idx, unit in enumerate(["", "万", "亿", "兆", "京"])] if s[0]])))("".join(reversed(str(number_string)))) or "零"
第一种方法
lambda seq:"".join(list(reversed([("%s%s" % (["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"][int(list(reversed(seq))[idx])], unit)) if idx>0 or int(list(reversed(seq))[1]) else ("零%s" % ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"][int(list(reversed(seq))[idx])]) for idx, unit in enumerate(reversed(reduce(list.__add__, [ ["仟", "佰", "拾", big_unit] for big_unit in ["兆", "亿", "万", ""]]))) if idx<len(seq) and int(list(reversed(seq))[idx])>0])))
第二种方法
lambda seq: "".join(reversed(["".join([prefix, ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"][int(num)], unit]) for prefix, num, unit in [["零", tp[0], tp[1]] if idx<(len(seq)-1) and int(seq[len(seq)-idx-2])<1 else ["", tp[0], tp[1]] for idx, tp in enumerate(zip(reversed(seq) , reversed(reduce(list.__add__, [ ["仟", "佰", " 拾", big_unit] for big_unit in ["兆", "亿", "万", ""]])))) if int(tp[0])]]))
@ipconfiger
Copy link
Author

千兆以下数字都可以转

@ipconfiger
Copy link
Author

表达式返回了一个lambda匿名函数, 赋值给一个对象就可以当函数用了, 只支持字符串输入

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment