简体   繁体   中英

Can I give the user an option to chose an element from the list based on its position in the list using python?

So I have two lists. The second list has more elements than the first. I want the user to chose one of the elements from the excess elements in the second list, but the names of these elements are very long so instead of typing out the names I would want the user to just chose which element in the list he wants based on their position in the list.

This is the code I have so far

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

What this will do is print out the new elements in the second list and allow the user to assign one of those elements to the parameter "Name".

But since the list elements in my actual code will be much longer I would like the user to be able to just enter the position of the element in the list and assign it to the "Name" attribute in that way.

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

Is there some way for me to do this? I would appreciate any help.

Thank you.

I'll break your problem down into little bits -

I'd use sets for the excess elements:

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

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

For accepting user input:

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

Processing user input:

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

When we enter 1:

Your choice is: Seven

I'll leave it up to you to combine these bits into a working program! You should have a thorough read of the python documentation - have a look at enumerate , list , set , and string formatting.

what about

index = raw_input()
index = int(index)

Your choice is ListOne[index-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM