我可以使用python给用户一个选项,根据元素在列表中的位置从列表中选择元素吗?

2024-05-16 05:59:40 发布

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

所以我有两张单子。第二个列表的元素比第一个多。我希望用户从第二个列表中多余的元素中选择一个元素,但是这些元素的名称非常长,因此我希望用户根据元素在列表中的位置来选择列表中的哪个元素,而不是键入名称。你知道吗

这是我目前掌握的密码

ListZero = ["One", "Two", "Three", "Four"]
ListOne = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
numberOfNew = -(len(ListOne) - len(ListZero))
Name = raw_input("Please choose which number you wish to use: %s \nYour choice is: " % (", ").join(ListOne[numberOfNew:]))
if Name not in (ListOne[numberOfNew:]):
    print "Error"
else:
    print Name

Example output:
Please choose which number you wish to use: Five, Six, Seven 
Your choice is: Seven
Seven

这将要做的是打印出第二个列表中的新元素,并允许用户将其中一个元素分配给参数“Name”。你知道吗

但是,由于我的实际代码中的列表元素将更长,我希望用户能够只输入列表中元素的位置,并以这种方式将其分配给“Name”属性。你知道吗

Example output:
Please choose which number you wish to use: Five[5], Six[6], Seven[7] 
Your choice is: 7
Seven

有什么办法让我这么做吗?如果有任何帮助,我将不胜感激。你知道吗

谢谢你。你知道吗


Tags: 用户nameyou元素numberwhich列表please
2条回答

我会把你的问题分解成小块-

对于多余的元素我会使用集合:

>>> set(ListOne) - set(ListZero)
set(['Seven', 'Six', 'Five'])

>>> Excess = list(set(ListOne)-set(ListZero))
['Seven', 'Six', 'Five']

接受用户输入:

>>> ExcessList = ["{0} [{1}]".format(name, index) for index, name in enumerate(Excess,1)]
['Seven [1]', 'Six [2]', 'Five [3]']

>>> Name = raw_input("Please choose which number you wish to use: {} \n".format(', '.join(ExcessList)))

Please choose which number you wish to use: Seven [1], Six [2], Five [3]

正在处理用户输入:

try:
    Selected = Excess[int(Name)-1]
    print "Your choice is: {}".format(Selected)
Except: 
    print "Invalid input"

当我们输入1:

Your choice is: Seven

我将让你把这些信息组合成一个工作程序!您应该全面阅读python文档—查看enumeratelistset和字符串格式。你知道吗

那怎么办

index = raw_input()
index = int(index)

您的选择是ListOne[index-1]

相关问题 更多 >