【问题标题】:Python For Loop Output IntegerPython For循环输出整数
【发布时间】:2018-01-08 16:16:17
【问题描述】:

这个 for 循环应该接受输入的输入并将字符转换为整数。

input = a
output = []
for char in input:
     num = ord(char) - 96
     output.append(num)

问题是最后输出等于“[1]”。

>>>print(output)
>>>[1]

我需要它是一个整数才能相乘。

【问题讨论】:

  • 那为什么要把它附加到一个列表中呢?
  • 为什么output 是一个列表开头?
  • 第一行应该是input = "a"吗?顺便说一句,您不应该使用 input 作为变量名,因为这会影响内置的 input 函数。
  • 到retrieve an item from a list,使用它的索引n = output[0]。
  • 你的输入是一个只包含数字的字符串吗?

标签: python for-loop integer


【解决方案1】:

ord() 方法返回一个整数,表示给定 Unicode 字符的 Unicode 代码点。

在您的情况下,您的输入为“a”,由数字表示:97

>>> print ord('a')
97

因此,当你从 97 中减去 96 时,你得到 1。

它已经是一个 int ....

>>> if type(ord('a')) is int:
...     print 'is int'
... else:
...     pass
...
is int

最后,如果你想将它相乘,请将你的操作符从“-”改为“*”...

>>> input = 'B'
>>> print ord(input) 
66

>>> output = []
>>> for char in input:
...     num = ord(char) * 2
...     print num
132

【讨论】:

  • 我认为 OP想要对ord(char) - 96的结果进行算术运算。
【解决方案2】:
input = a
output = []
total = 0;
for char in input:
    num = int(char)
    total = (total*10)+num

我的回答假设输入是一个数字,但采用字符串格式,并且您希望对其进行迭代。因为如果数量很少,您可以这样做:

int(input)

我需要更多解释来澄清我的答案。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 2019-05-12
    相关资源
    最近更新 更多