我如何创建一个列表,然后 len() 它,然后在 Python 中为该列表中的每个 'section' 创建一个条目?

How do I create a list, then len() it, then make an entry for every 'section' in that list in Python?

所以,我正在做一个项目,它要求我找出一个列表中有多少 'objects',我通过 len() 完成了这项工作,但是,现在我需要做到这一点对于该列表中的每个条目都有一个选择(在 easygui 的 choicebox() 中),而不会引发 'out of range' 异常。

基本上,如果列表中有3个条目,那么我需要choicebox(msg="",title="",choices=[e[1])变成choicebox(msg="",title="",choices=[e[1],e[2],e[3]]),如果有5个选择,我需要它变成choicebox(msg="",title="",choices=[e[1],e[2],e[3],e[4],e[5]])和等等。

注意:我需要跳过 e[0],即 .DS_Storedesktop.inithumbs.db
我在此之前列出了目录,所以如果你能告诉我如何只使目录最终出现在列表中,或者甚至如何将条目限制为 22 个,那也将不胜感激!!

抱歉这个菜鸟问题!我想不出如何搜索这样的东西,或者合适的标题......

编辑:这是我应要求编写的脚本。它几乎没有错误,但非常不完整和损坏;

#imports
from easygui import *
import os
#variables
storyname = None
#get user action
def selectaction():
    d = str(buttonbox(msg="What would you to do?",title="Please Select an Action.",choices=["View Program Info","Start Reading!","Exit"]))
    if d == "View Program Info":
        msgbox(msg="This program was made solely by Thecheater887. Program Version 1.0.0.               Many thanks to the following Story Authors;                                                Thecheater887 (Cheet)",title="About",ok_button="Oh.")
        selectaction()
    elif d == "Exit":
        exit
    else:
        enterage()
#get reader age
def enterage():
    c = os.getcwd()
#   print c
    b = str(enterbox(msg="Please enter your age",title="Please enter your age",default="Age",strip=True))
#   print str(b)
    if b == "None":
        exit()
    elif b == "Age":
        msgbox(msg="No. Enter your age. Not 'Age'...",title="Let's try that again...",ok_button="Fine...")
        enterage()
    elif b == "13":
#       print "13"
        choosetk()
    elif b >= "100":
        msgbox(msg="Please enter a valid age between 0 and 100.",title="Invalid Age!")
        enterage()
    elif b >= "14":
#       print ">12"
        choosema()
    elif b <= "12":
#       print "<12"
        choosek()
    else:
        fatalerror()
#choose a kids' story
def choosek():
    os.chdir("./Desktop/Stories/Kid")
    f = str(os.getlogin())
    g = "/Users/"
    h = "/Desktop/Stories/Kid"
    i = g+f+h
    e = os.listdir(i)
    names = [name for name in e if name not in ('.DS_Store', 'desktop.ini', 'thumbs.db')]
    limit = 22 # maximum entries in the choicebox --> e[1] until e[22]
    for i in xrange(1, len(e)): # starting from 1 because you don't want e[0] in there
        if(i > limit):
            break # so if you have 100 files, it will only list the first 22
        else:
            names.append(e[i])
        #names = e[1:23]
    choicebox(msg="Please select a story.",title="Please Select a Story",choices=names)
#choose a mature story
def choosema():
    os.chdir("./Desktop/Stories/Mature")
#choose a teen's story
def choosetk():
    os.chdir("./Desktop/Stories/Teen")
def fatalerror():
    msgbox(msg="A fatal error has occured. The program must now exit.",title="Fatal Error!",ok_button="Terminate Program")
#select a kids' story
def noneavailable():
    msgbox(msg="No stories are available at this time. Please check back later!",title="No Stories Available",ok_button="Return to Menu")
    enterage()
selectaction()

所以这是我的解决方案(现在我有了代码):

def choosek():
    os.chdir("./Desktop/Stories/Kid")
    f = str(os.getlogin())
    g = "/Users/"
    h = "/Desktop/Stories/Kid"
    i = g+f+h
    e = os.listdir(i)
    names = [] # the list with the file names
    limit = 22 # maximum entries in the choicebox --> e[1] until e[22]
    for i in xrange(1, len(e)): # starting from 1 because you don't want e[0] in there
        if(i > limit):
            break # so if you have 100 files, it will only list the first 22
        else:
            names.append(e[i])
    choicebox(msg="Please select a story.",title="Please Select a Story",choices=names)

希望这就是您要找的。

如果您想从现有列表创建一个新列表,但它不应包含第一个元素,那么您可以使用切片表示法:list[start:end]。如果您省略 start,它将从第一个元素开始。如果您省略末尾,它将继续到列表的末尾。

因此,要省略第一个元素,您可以这样写:

names = e[1:]

如果你想要最多22个元素,写:

names = e[1:23]

如果原始列表包含的元素少于 23 个,则新列表将尽可能多地包含元素。如果它包含更多,那么您将最多获得 22 个元素 (23 - 1)。

如果你想跳过某些元素,你可以使用列表理解:[item-expression for item in list (if filter-expression)],其中过滤器表达式部分是可选的。

这也可用于复制列表:

names = [name for name in e]

您可以添加一个过滤器来排除不需要的元素,如下所示:

names = [name for name in e if name not in ('.DS_Store', 'desktop.ini', 'thumbs.db')]