Python,从输入的元组返回整数

2024-09-27 00:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使输入命令简化,我不知道是否可以解释这一点,但它在这里

    out = input()
    planOne = int(out)
    planet = listplanets[planOne]
    print(planet)

所以listplanets是一个元组,如果我输入一个像0这样的数字,它将返回Mercury,我如何使它可以输入mercury,它将返回Mercury。我希望保持元组格式,并且我还需要元组项的整数值,例如var1。如果有人能帮我,我将不胜感激。PS我知道,我是一个巨大的NoobXD。 编辑:这就是我的元组的制作方法

listplanets = ("Mercury"), (0.378), ("Venus"), (0.907), ("Mars"), (0.377), ("Io"), (0.1835), ("Europa"), (0.1335), ("Ganymede"), (0.1448), ("Callisto"), (0.1264)

编辑: 正如你们善良的人们所建议的,我现在正在使用字典

    listplanets = {
        "Mercury": "Mercury",
        "Mercury2": 0.378,
        "Venus": "Venus",
        "Venus2": 0.907,
        "Mars": "Mars",
        "Mars2": 0.377,
        "Io": "Io",
        "Io2": 0.1835,
        "Europa": "Europa",
        "Europa2": 0.1335,
        "Ganymede": "Ganymede",
        "Ganymede2": 0.1448,
        "Callisto": "Callisto",
        "Callisto2": 0.1264}

我这样构造它的原因是为了打印,我把它复杂化了! 我不确定问另一个问题是否违反规定,但它确实与这篇文章有关。 我现在正在尝试使用它,因此当您键入mercury它将输出On the planet of Mercury,下面的代码对我不起作用,如果您能提供更多帮助,我们将不胜感激

    out = input().capitalize()
    if out == listplanets:
        print("On the planet of", listplanets[out])
    else:
        print("That was an incorrect format! Try again.")
        planets()

对于任何好奇的人,这里是我的代码(之所以不是文本是因为这是我的任务,反瘟疫工具会说我在复制我自己的代码!XD): First part of the code

Second part

Last part

This didn't show clearly

---------------------------------------

前面的部分没有清楚地显示出来,这就是为什么那里有一个图像 enter image description here


Tags: 代码ioinputout元组printmarsmercury
3条回答

不能在字典上直接使用切片运算符listplanets[out]

你不必一遍又一遍地重复同样的事情。 将此格式用于词典

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

这个代码怎么样

# 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'

如果需要保持元组格式,则必须像这样循环数据:

# 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]))

但正如评论中提到的,使用字典要好得多

相关问题 更多 >

    热门问题