【问题标题】:How do I create a list, then len() it, then make an entry for every 'section' in that list in Python?如何创建一个列表,然后 len() 它,然后在 Python 中为该列表中的每个“部分”创建一个条目?
【发布时间】:2015-01-11 01:07:12
【问题描述】:

所以,我正在做一个项目,这需要我找出列表中有多少“对象”,我通过len() 完成了这项工作,但是,现在我需要在有选择的地方进行(在 easygui 的 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 个,那也将不胜感激!!

很抱歉提出了一个愚蠢的问题!我想不出如何搜索这样的东西,或者一个合适的标题......

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

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

【问题讨论】:

  • 你能至少提供一些代码吗?
  • @ProgrammingIsAwesome 你想让我发布我的脚本吗?我以为我提供了足够的信息,但显然你也想窃取我的工作......
  • 现在我不想偷东西了。但如果你写:我有清单,那么我会做的。我不知道你什么时候做你的步骤。提供您的脚本或其中的一部分,以便我可以提供帮助
  • 很好。编辑成 OP。
  • @Thecheater887 好笑。你真的认为有人真的想窃取你的代码吗?

标签: python list python-2.7 split easygui


【解决方案1】:

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

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)

我希望这就是你要找的。​​p>

【讨论】:

  • 不客气。您会看到没有人想窃取您的代码。但是如果没有您的代码 sn-p(函数 choosek() 就足够了),我将无法为您提供帮助。
  • 虽然这可行,并且在类似 C 的语言中可能很自然,但它并不是一种非常“Pythonic”的方式。
  • @PieterWitvoet:你是对的。但我认为如果你学习 Python,它会更清楚。我知道这不是一种非常 Pythonic 的方式。
【解决方案2】:

如果您想从现有列表创建一个新列表,但它不应该包含第一个元素,那么您可以使用切片表示法: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')]

【讨论】:

  • 好的,谢谢你的过滤器,但是,它只过滤掉列表中的第一项,这意味着,在这种情况下,它过滤掉了.DS_Store。我怎样才能让它过滤掉所有 3 个?
  • 如果你写的和我写的完全一样,那么它应该过滤掉所有 3 个。括号很重要(尽管你可以用方括号替换它们,因为 in 运算符适用于任何序列类型) .
  • 不。还是不行。嗯......它足以过滤掉第一个,但不是第二个和第三个。如果您想自己测试,我在 OP 中更新了我的脚本。
  • 那是因为您在运行列表理解后将所有项目从e 附加到names。要过滤并将列表限制为 22 个项目,请将列表推导式与切片表示法相结合:names = [name for name in e if name not in ('.DS_Store', 'desktop.ini', 'thumbs.db')][1:23]。然后不要将任何内容附加到names
  • 但是如果有 3 个目录,我需要它有 3 个选择,如果有 15 个目录,我需要它有 15 个选择。如果不附加,我将如何做到这一点?
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
相关资源
最近更新 更多