python -Roman数字转换器" TypeError:' int'对象不可迭代"

时间:2017-05-31 10:45:16

标签: python typeerror roman-numerals

我对编码仍然很陌生,而且我一直试图完成朋友给我的挑战。我必须将用户的数字列表转换为罗马数字。然而,我得到了一个" TypeError:' int'对象不可迭代"我使用的第二个功能。

def romanizer(n, arr):

    output = []

    for i in range(n):
        individual = arr.pop(0)
        x = convert(individual)
        output.append(x)

    print output

def convert(num):

    roman_table = { 1000: 'M', 900: 'CM', 500: 'D',
                    400: 'CD' , 100: 'C', 90: 'XC',
                    50: 'L', 40: 'XL', 10: 'X', 
                    9: 'IX', 5: 'V', 4: 'IV',
                    1: 'I'}  

    roman = ''
    while num > 0:
        for number, numeral in roman_table: # This is where the error sends me
            while num >= number:
                roman += numeral
                num -= number 

    return roman

units = int(raw_input("How many numbers must be converted? "))
numbers = raw_input("Which numbers? ")
converted = list(map(int, numbers.split()))

print units
print numbers

romanizer(units, converted)

执行以下输入后出现以下错误:

How many numbers must be converted? 2
Which numbers? 111 506
2
111 506

Traceback (most recent call last):
  File "romanizer.py", line 37, in <module>
    romanizer(units, converted)
  File "romanizer.py", line 9, in romanizer
    x = convert(individual)
  File "romanizer.py", line 24, in convert
    for number, numeral in roman_table:
TypeError: 'int' object is not iterable

如果可能的话,有人可以帮助我吗?我不确定为什么我会收到错误,因为它应该使用该数字来迭代我已经设置的条件。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

在字典上循环只会产生,但是你试图将每个键分配给两个变量:

for number, numeral in roman_table:

您的密钥是整数,因此循环尝试执行此操作:

>>> number, numeral = 1000
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

给你例外。

循环遍历roman_table.items()

for number, numeral in roman_table.items():

但是,字典无序。你真的想先从罗马数字开始,而不是只用任何,所以排序你的项目:

for number, numeral in sorted(roman_table.items(), reverse=True):

排序也有成本;你可能想把你的表列为序列,而不是字典,所以你可以避免排序:

roman_table = [
    (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'),
    (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'),
    (4, 'IV'), (1, 'I')
]

for number, numeral in roman_table:

该表现在是一个元组列表,因此不再需要使用.items()

使用反向排序表,您可以获得正确的输出:

>>> convert(111)
'CXI'
>>> convert(506)
'DVI'
>>> convert(999)
'CMXCIX'