3 回答
TA贡献1943条经验 获得超7个赞
您不能直接listplanets[out]在字典上使用切片运算符。
而且您不必一遍又一遍地重复同样的事情"mercury": "Mercury"。将此格式用于您的字典,
listplanets = {"Mercury": 0.378, "Venus": 0.907, "Mars": 0.377, "Io": 0.1835, "Europa": 0.1335, "Ganymede": 0.1448, "Call
试试这个
out = input()
if out.isdigit(): #check if the input is digit
print(list(listplanets.keys())[int(out)]) #gets all key values to a list and so slicing can done
else:
print(listplanets[out.capitalize()]) #capitalize first letter
TA贡献2003条经验 获得超2个赞
如果您需要保持元组格式,则必须像这样遍历数据:
# Data is given like this. First name and then value related to it.
listplanets = ("Mercury"), (0.378), ("Venus"), (0.907), ("Mars"), (0.377), ("Io"), (0.1835), ("Europa"), (0.1335), ("Ganymede"), (0.1448), ("Callisto"), (0.1264)
out = input("Planet: ")
for i in range(len(listplanets)):
if isinstance(listplanets[i], float):
# Skip values
continue
if out.lower() == listplanets[i].lower():
print ("{}: {}".format(listplanets[i], listplanets[i+1]))
但是正如评论中提到的,使用字典要好得多。
TA贡献1898条经验 获得超8个赞
这段代码怎么样?
# listplanets = ('Mercury', 'Earth')
In [19]: new_listplanets = [(index, {planet.lower(): planet}) for index, planet in enumerate(listplanets)]
# [(0, {'mercury': 'Mercury'}), (1, {'earth': 'Earth'})]
In [20]: new_listplanets[0][0]
Out[20]: 0
In [21]: new_listplanets[0][1]['mercury']
Out[21]: 'Mercury'
添加回答
举报