【发布时间】:2014-03-06 22:02:01
【问题描述】:
这两天我一直在努力解决这个问题。我是 python 和编程的新手,所以此类错误的其他示例对我没有太大帮助。我正在阅读列表和元组的文档,但没有找到任何有用的东西。任何指针将不胜感激。不一定要寻找答案,只是寻找更多资源。我正在使用 Python 2.7.6。谢谢
measure = raw_input("How would you like to measure the coins? Enter 1 for grams 2 for pounds. ")
coin_args = [
["pennies", '2.5', '50.0', '.01']
["nickles", '5.0', '40.0', '.05']
["dimes", '2.268', '50.0', '.1']
["quarters", '5.67', '40.0', '.25']
]
if measure == 2:
for coin, coin_weight, rolls, worth in coin_args:
print "Enter the weight of your %s" % (coin)
weight = float(raw_input())
convert2grams = weight * 453.592
num_coin = convert2grams / (float(coin_weight))
num_roll = round(num_coin / (float(rolls)))
amount = round(num_coin * (float(worth)), 2)
print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)
else:
for coin, coin_weight, rolls, worth in coin_args:
print "Enter the weight of your %s" % (coin)
weight = float(raw_input())
num_coin = weight / (float(coin_weight))
num_roll = round(num_coin / (float(rolls)))
amount = round(num_coin * (float(worth)), 2)
print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)
这是堆栈跟踪:
File ".\coin_estimator_by_weight.py", line 5, in <module>
["nickles", '5.0', '40.0', '.05']
TypeError: list indices must be integers, not tuple
【问题讨论】:
-
您不会解析来自
raw_input的结果。它永远不会是2。 -
由于您两次编写或多或少相同的源代码,您应该考虑如何使这更优雅。其实你只需要区分重量单位,根据需要转换输入,其余的都一样。
-
OBu 一个很好的观点。我将努力改进我的代码。我假设您正在谈论制作功能。