gpt4 book ai didi

python - 变量在某个地方失去了它的值(value)

转载 作者:太空宇宙 更新时间:2023-11-04 10:00:09 25 4
gpt4 key购买 nike

我一直在研究一个循环的罗马数字转换器,直到被告知退出并且它工作......在第一次迭代中。变量之后就是空的,这可能与我分配它的位置有关?

代码:

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

def int_to_roman(i):
result = []
for integer, numeral in num_array:
count = int(i / integer)
result.append(numeral * count)
i -= integer * count
return ''.join(result)

def roman_to_int(n):
result = 0
i = result
for integer, numeral in num_array:
while n[i:i + len(numeral)] == numeral:
result += integer
i += len(numeral)
return result

x = ""
while x != "quit":
x = ""
x = input("enter number to be converted or quit to stop ")
if x == "quit":
break
else:
if x.isdigit():
x = int(x)
print(x, 'is',(int_to_roman(x)))
print(' ')
else:
if x.isalpha():
print(x,'is',(roman_to_int(x)))
print(' ')

输出:

enter number to be converted or quit to stop C
C is 100

enter number to be converted or quit to stop C
C is 0

enter number to be converted or quit to stop

最佳答案

在 Python3 中,zip 返回一个可迭代对象。第一次调用后,zip 的结果已经被消费了。您可以从 zip 的结果创建一个 list 而不是

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

用更小的例子更容易理解

>>> nums = zip((1, 2, 3, 4), ('A', 'B', 'C', 'D'))
>>> nums
<zip object at 0x7f5a860cba08>
>>> for item in nums:
... print(item)
...
(1, 'A')
(2, 'B')
(3, 'C')
(4, 'D')
>>> for item in nums: # Nothing left in zip object
... print(item)
...
>>> nums = list(zip((1, 2, 3, 4), ('A', 'B', 'C', 'D')))
>>> nums
[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D')]
>>> for item in nums:
... print(item)
...
(1, 'A')
(2, 'B')
(3, 'C')
(4, 'D')
>>> for item in nums: # Can loop over a list as many times as you like
... print(item)
...
(1, 'A')
(2, 'B')
(3, 'C')
(4, 'D')
>>>

关于python - 变量在某个地方失去了它的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43971368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com