Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以给用户一个选项,使用python根据元素在列表中的位置从列表中选择元素吗?_Python_Python 2.7 - Fatal编程技术网

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

我可以给用户一个选项,使用python根据元素在列表中的位置从列表中选择元素吗?,python,python-2.7,Python,Python 2.7,所以我有两个清单。第二个列表的元素比第一个列表的元素多。我希望用户从第二个列表中的多余元素中选择一个元素,但是这些元素的名称非常长,因此我希望用户根据它们在列表中的位置选择列表中的元素,而不是键入名称 这是我目前掌握的代码 ListZero = ["One", "Two", "Three", "Four"] ListOne = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"] numberOfNew = -(len(ListOne)

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

这是我目前掌握的代码

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
有什么办法让我这么做吗?我将感谢任何帮助

谢谢。

怎么样

index = raw_input()
index = int(index)

您的选择是ListOne[index-1]

我将把您的问题分解为几点-

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

>>> 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)))
try:
    Selected = Excess[int(Name)-1]
    print "Your choice is: {}".format(Selected)
Except: 
    print "Invalid input"
请选择您希望使用的数字:七[1],六[2],五[3]

处理用户输入:

>>> 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)))
try:
    Selected = Excess[int(Name)-1]
    print "Your choice is: {}".format(Selected)
Except: 
    print "Invalid input"
当我们输入1时:

你的选择是:七

我将让您将这些位组合成一个工作程序!您应该彻底阅读python文档—查看
枚举
列表
,以及字符串格式