[英]Getting this output, with generators/list comprehensions?
I'm having a bit of trouble with something, and I don't know how I could do it. 我遇到了一些问题,我不知道怎么做。
Well, I'm creating a dynamic form with buttons that adapts to how many files (in this case, movies) there are in a directory. 好吧,我正在创建一个带有按钮的动态表单,这些按钮可以适应目录中有多少文件(在本例中为电影)。
I have got this so far: 到目前为止我有这个:
path="C:\\Users\\User\\Desktop\\test\\" # insert the path to the directory of interest
movies = []
dirList=os.listdir(path)
for fname in dirList: # loops through directory specified
print fname # prints file name
movies.append(fname) # adds the file name to list
my_form = form.Form([form.Button("btn", id="btn" + movies[i], value = i, html=movies[i], class_="btn" +movies[i]) for i in range(len(movies))])
However, I want the list comprehension/generator to make my_form
look something like this: 但是,我希望list comprehension / generator使my_form
看起来像这样:
my_form = form.Form(
form.Button("btn", id="btnA", value="A", html="Movie1", class_="btnA")
form.Button("btn", id="btnB", value="B", html="Movie2", class_="btnB")
)
As you can see instead of the movie name being the id, it is btnA
or btnB
. 正如您所看到的,而不是电影名称是id,它是btnA
或btnB
。
So how could I generate that output? 那我怎么能产生那个输出呢?
I think you want to do something like: 我想你想做的事情如下:
from string import ascii_uppercase
buttons = [form.Button("btn", id="btn{0}".format(char), value=char,
html=movie, class_="btn{0}".format(char))
for char, movie in zip(ascii_uppercase, movies)]
my_form = form.Form(buttons)
This uses the letters in string.ascii_uppercase
to label each item in movies
. 这使用string.ascii_uppercase
的字母标记movies
每个项目。
If I understand correctly, you want the id to be btn + a letter according to the index of the movie? 如果我理解正确,你想根据电影的索引将id设为btn +一个字母?
you can use this code: 你可以使用这段代码:
def letterForIndex(idx):
return chr(ord('A')+idx)
so you would do : 所以你会这样做:
my_form = form.Form([form.Button("btn", id="btn" + letterForIndex(i),
value = letterForIndex(i), html=movies[i], class_="btn" +letterForIndex(i)) for i in range(len(movies))])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.