将 int 转换为单个数字列表更快?
所有,
我想定义一个 int(987654321) <=> [9, 8, 7, 6, 5, 4, 3, 2, 1] 转换器,如果 int 数字的长度 9,例如 10 列表将为 [0,0,0,0,0,0,0,1,0] ,并且如果长度> 9,例如 9987654321 ,列表将为 [9, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> i
987654321
>>> l
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> z = [0]*(len(unit) - len(str(l)))
>>> z.extend(l)
>>> l = z
>>> unit
[100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1]
>>> sum([x*y for x,y in zip(l, unit)])
987654321
>>> int("".join([str(x) for x in l]))
987654321
>>> l1 = [int(x) for x in str(i)]
>>> z = [0]*(len(unit) - len(str(l1)))
>>> z.extend(l1)
>>> l1 = z
>>> l1
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> a = [i//x for x in unit]
>>> b = [a[x] - a[x-1]*10 for x in range(9)]
>>> if len(b) = len(a): b[0] = a[0] # fix the a[-1] issue
>>> b
[9, 8, 7, 6, 5, 4, 3, 2, 1]
我测试了上述解决方案,但发现这些解决方案可能比我想要的更快/简单,并且可能有内部与长度相关的错误,任何人都可以与我分享这种转换的更好解决方案吗?
谢谢!
All,
I want define an int(987654321) <=> [9, 8, 7, 6, 5, 4, 3, 2, 1] convertor, if the length of int number < 9, for example 10 the list will be [0,0,0,0,0,0,0,1,0]
, and if the length > 9, for example 9987654321 , the list will be [9, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> i
987654321
>>> l
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> z = [0]*(len(unit) - len(str(l)))
>>> z.extend(l)
>>> l = z
>>> unit
[100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1]
>>> sum([x*y for x,y in zip(l, unit)])
987654321
>>> int("".join([str(x) for x in l]))
987654321
>>> l1 = [int(x) for x in str(i)]
>>> z = [0]*(len(unit) - len(str(l1)))
>>> z.extend(l1)
>>> l1 = z
>>> l1
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> a = [i//x for x in unit]
>>> b = [a[x] - a[x-1]*10 for x in range(9)]
>>> if len(b) = len(a): b[0] = a[0] # fix the a[-1] issue
>>> b
[9, 8, 7, 6, 5, 4, 3, 2, 1]
I tested above solutions but found those may not faster/simple enough than I want and may have a length related bug inside, anyone may share me a better solution for this kinds convertion?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许我错过了一些东西,但这还不够吗(没有价值检查)?
参考:
str.zfill
Maybe I am missing something, but shouldn't this be enough (without value checking)?
Reference:
str.zfill
那么呢:
And what about :
将任意长度的整数按整数位顺序放入列表中 -
输出 -
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7 , 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5 , 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
可以将条件放在 j 上,以替代赋值给 b。
To place an integer of any length into a list in sequence by integer digit -
output -
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
you can put the condition on j for the alternate assignment to b.