如何操作整数/字符串中的数字?
我正在寻找一种通用方法来引用整数或字符串中的特定数字,我需要能够对交替数字执行不同的操作并对所有这些返回值的结果求和。
非常感谢任何帮助
哦,我是一个完全的初学者,所以防白痴的答案将不胜感激。
我将详细说明,Python上是否有任何内置函数可以将整数减少为数字列表,我看起来无济于事,我希望这里有人能理解我在问什么,抱歉这么含糊,但我确实这样做对 Python 的了解还不够,无法提出非常深入的问题。
I am looking for a general way to refer to particular digits in a integer or string, I need to be able to perform different operations on alternating digits and sum the result of all of those returned values.
Any help is much appreciated
Oh and I am a complete beginner so idiot-proof answers would be appreciated.
I will elaborate, is there any inbuilt function on Python that could reduce an integer into a list of it's digits, I have looked to no avail and I was hoping someone here would understand what I was asking, sorry to be so vague but I do not know enough of Python yet to provide a very in-depth question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您从整数开始,请首先将其转换为字符串;您无法方便地寻址整数中的数字:
用方括号中的索引来寻址各个数字,从零开始:
如果您需要对它们进行数学运算,则将这些数字转换回整数:
如果您只是在做数字命理学求和、列表推导式很方便:
只要记住,当你考虑单个数字时,你正在使用字符串,而当你进行算术运算时,你正在使用整数,所以这种事情需要很多转换的 来回。
If you're starting with an integer, first convert it to a string; you can't address the digits within an integer conveniently:
Address individual digits with their index in square brackets, starting from zero:
Convert those digits back to integers if you need to do math on them:
And if you're just doing a numerological summation, list comprehensions are convenient:
Just keep in mind that when you're considering individual digits, you're working with strings, and when you're doing arithmetic, you're working with integers, so this kind of thing requires a lot of conversion back and forth.
将字符串转换为数字列表:
列表是可变的,因此您可以通过这种方式修改单个数字。
转换回字符串(假设所有数字都是单位值):
并且您可以在切片中使用步幅来处理交替数字
To just convert a string to a list of digits:
Lists are mutable, so you can modify individual digits this way.
Converting back to a string (assuming all your numbers are single-digit values):
And you can use strides in slicing to deal with alternating digits
我不会声称这是最好的答案,但它满足您的要求:
或者,如果您的输入已经是字符串,您可以省略
str()
转换:从那里您可以修改根据需要生成列表...
I'm not going to claim this is the best answer, but it meets your requirements:
Or, if your input is already a string you can omit the
str()
cast:From there you can modify the resulting list as needed...