Python - 将用户输入整数拆分为列表,其中每个条目为2位数 [英] Python - Split user input integer into list, where each entry is 2 digits

查看:2189
本文介绍了Python - 将用户输入整数拆分为列表,其中每个条目为2位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图将一个任意长的用户输入整数分成一个列表,其中每个条目是2位数,如果该数字有一个奇数的整数,则将唯一的一位数作为第一个数字。 (然后我将继续在它前面加零)

So I'm trying to split an arbitrarily long user input integer into a list where each entry is 2 digits, and if the number has an odd amount of integers put the only single digit as the first digit. (Where I will then proceed to put a zero in front of it)

我知道将用户整数输入放入列表中如下所示:

I know that putting user integer input into a list looks like:

userintegerlist = [int(i) for i in str(user_input)]
print userintegerlist

我的输入(比如 45346 )看起来像 [4, 5,3,4,6] 。但我希望它看起来像: [4,53,46] 。或者,如果输入为 68482238 ,则输入为: [68,48,22,38]

And my input (say it's 45346) will look like [4,5,3,4,6]. But I want it to look like: [4,53,46]. Or if input is 68482238, it will be: [68,48,22,38].

这可能吗?顺便说一下,所有的代码都在Python中。

Is this possible? All the code is in Python by the way.

推荐答案

你可以很容易地使用字符串方法,因为其他答案已经所示。我将引导您访问相关的 itertools中的石斑鱼食谱

You can do it with string methods fairly easily, as other answers have already shown. I direct you to the related grouper recipe in itertools.

我想提一下,用数学做这件事可能更有效率:

I want to mention that it may be more efficient to do it with maths:

>>> n = 45346
>>> output = []
>>> while n:
...     output.append(n % 100)
...     n //= 100
...     
>>> output = output[::-1]
>>> print output
[4, 53, 46]

这篇关于Python - 将用户输入整数拆分为列表,其中每个条目为2位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆