如何创建一个列表,然后是len()它,然后为Python中该列表中的每个“部分”创建一个条目?

时间:2015-01-11 01:07:12

标签: python list python-2.7 split easygui

所以,我正在开展一个项目,这需要我找到多少'对象'在我通过len()完成的列表中,但是,现在我需要在该列表中的每个条目中选择(在easygui' s choicebox()中),而不需要提高超出范围'异常。

基本上,如果列表中有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,那么我们也非常感激! !

抱歉这个noobish问题!我无法想到如何搜索这样的东西,甚至是一个适合的标题......

编辑:根据请求,这是我的脚本。它几乎没有漏洞,但非常不完整和破碎;

#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()

2 个答案:

答案 0 :(得分:2)

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

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)

我希望这就是你要找的东西。

答案 1 :(得分:0)

如果要从现有列表创建新列表,除了它不应包含第一个元素,则可以使用切片表示法: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)],其中filter-expression部分是可选的。

这也可用于制作列表的副本:

names = [name for name in e]

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

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