Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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
如何创建一个列表,然后len()创建它,然后在Python中为该列表中的每个“部分”创建一个条目?_Python_List_Python 2.7_Split_Easygui - Fatal编程技术网

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

如何创建一个列表,然后len()创建它,然后在Python中为该列表中的每个“部分”创建一个条目?,python,list,python-2.7,split,easygui,Python,List,Python 2.7,Split,Easygui,所以,我正在做一个项目,这要求我找出列表中有多少“对象”,这是我通过len完成的,但是,现在我需要在easygui的choicebox中为列表中的每个条目进行选择,而不会引发“超出范围”的异常 基本上,如果列表中有3个条目,那么我需要choiceboxmsg=,title=,choices=[e[1]变成choiceboxmsg=,title=,choices=[e[1],e[2],e[3]],如果有5个选项,我需要它变成choiceboxmsg=,title=,choices=[e[1],e[

所以,我正在做一个项目,这要求我找出列表中有多少“对象”,这是我通过len完成的,但是,现在我需要在easygui的choicebox中为列表中的每个条目进行选择,而不会引发“超出范围”的异常

基本上,如果列表中有3个条目,那么我需要choiceboxmsg=,title=,choices=[e[1]变成choiceboxmsg=,title=,choices=[e[1],e[2],e[3]],如果有5个选项,我需要它变成choiceboxmsg=,title=,choices=[e[1],e[2],e[3],e[4],e[5]]等等

注意:我需要跳过e[0],即.DS_Store、desktop.ini或thumbs.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]。如果您省略了开头,它将从第一个元素开始。如果您省略了结尾,它将继续到列表的结尾

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

名称=e[1:]

如果最多需要22个元素,请编写:

名称=e[1:23]

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

如果要跳过某些元素,可以对其使用列表理解:[item expression for item in list If filter expression],其中filter expression部分是可选的

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

名称=[在e中名称的名称]

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


名称=[如果名称不在“.DS_Store”、“desktop.ini”、“thumbs.db”中,则名称在e中的名称]

你至少能提供一些代码吗?@Programming Isawesome你想让我发布我的脚本吗?我以为我提供了足够的信息,但显然你也想偷我的作品……现在我不想偷任何东西。但如果你写:我有列表,我会做。我不知道你什么时候做你的步骤。提供你的脚本或其中的一部分o我可以帮忙。编辑成OP.@Thecheater887搞笑。你真的认为有人真的想偷你的代码吗?不客气。你知道没有人想偷你的代码。但是如果没有你的代码片段,函数choosek就足够了,我就无法帮你了。虽然这很有效,而且在类似C的l中可能是很自然的语言,这不是一种很“Python”的方式。@PieterWitvoet:你是对的。但我认为如果你学习Python,它会更清晰。我知道这不是一种很“Python”的方式。好吧,谢谢你的过滤功能,但是,它只过滤掉列表中的第一项,也就是说,在本例中,它过滤掉了。d_Store。我如何让它过滤掉所有3项?如果你写了正是我写的,然后它应该过滤掉所有3个。括号很重要,尽管你可以用方括号替换它们,因为in运算符可以处理任何序列类型。不,仍然不起作用。好吧……它可以过滤掉第一个,但不能过滤掉第二个和第三个。如果你想测试I,我在OP中更新了我的脚本t您自己。这是因为在运行列表理解后,您正在将e中的所有项目添加到名称中。若要筛选列表并将其限制为22个项目,请将列表理解与切片表示法结合起来:name=[如果名称不在.DS_Store'、.desktop.ini'、.thumbs.db']中,则在e中为名称命名][1:23]。然后不要在名称后面附加任何内容。但是如果有3个目录,我需要它有3个选项,如果有15个目录,我需要它有15个选项。如果没有附加,我怎么做呢?