Enumerate items in a list so a user can select the numeric value

邮差的信 提交于 2019-12-23 22:58:00

问题


I'm trying to find the most straightforward way to enumerate items in a list so that a user will not be burdened to type a long file name on a command line. The function below shows a user all .tgz and .tar files in a folder ... the user is then allowed to enter the name of the file he wants to extract. This is tedious and syntax-error prone for the user. I would like for a user to just select, say, a numeric value associated with the file (eg.. 1, 2, 3 etc.). Can someone give me some direction on this? Thanks!

  dirlist=os.listdir(path)

  def show_tgz():
     for fname in dirlist:
          if fname.endswith(('.tgz','.tar')):
             print '\n'
             print fname

回答1:


You can enumerate the items, and print them with an index. You can use a mapping to show continuous numbers to the user, even if the actual indices have gaps:

 def show_tgz():
     count = 1
     indexMapping = {}
     for i, fname in enumerate(dirlist):
         if fname.endswith(('.tgz','.tar')):
             print '\n{0:3d} - {1}'.format(count, fname)
             indexMapping[count] = i
             count += 1
     return indexMapping

You can then use indexMapping to translate the userchoice to the correct index in dirlist.




回答2:


Start with a list of files:

files = [fname for fname in os.listdir(path) 
               if fname.endswith(('.tgz','.tar'))]

Now you can literally enumerate them:

for item in enumerate(files):
    print "[%d] %s" % item

try:
    idx = int(raw_input("Enter the file's number"))
except ValueError:
    print "You fail at typing numbers."

try:
    chosen = files[idx]
except IndexError:
    print "Try a number in range next time."



回答3:


def gen_archives(path):
    names = os.listdir(path)
    for name in names:
        if name.endswith(('.tgz', '.tar'))
            yield name

for i, name in enumerate( gen_archives(path) ):
    print "%d. %s" % (i, name)



回答4:


I really liked Jochen's answer, but disliked the multiple try/except. Here's a variation using a dict instead, which will loop until a valid selection is made.

files = dict((str(i), f) for i, f in
              enumerate(f for f in os.listdir(path) if f.endswith(('.tgz','.tar'))))
for item in sorted(files.items()):
    print '[%s] %s' % item
choice = None
while choice is None:
    choice = files.get(raw_input('Enter selection'))
    if not choice:
        print 'Please make a valid selection'


来源:https://stackoverflow.com/questions/6410982/enumerate-items-in-a-list-so-a-user-can-select-the-numeric-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!