为什么第一个“标题”列表不起作用而第二个起作用?我如何使第一个工作? 谢谢!
highlighted_poems = "Afterimages:Audre Lorde:1997, The Shadow:William Carlos Williams:1915, Ecstasy:Gabriela Mistral:1925, Georgia Dusk:Jean Toomer:1923, Parting Before Daybreak:An Qi:2014, The Untold Want:Walt Whitman:1871, Mr. Grumpledump's Song:Shel Silverstein:2004, Angel Sound Mexico City:Carmen Boullosa:2013, In Love:Kamala Suraiyya:1965, Dream Variations:Langston Hughes:1994, Dreamwood:Adrienne Rich:1987"
highlighted_poems_list = highlighted_poems.split(',')
highlighted_poems_stripped = [line.strip() for line in highlighted_poems_list]
highlighted_poems_details = [line.split(':') for line in highlighted_poems_stripped]
print(highlighted_poems_details)
print()
print()
print()
print(highlighted_poems_details[1][1])
titles = [titles.append(title[0]) for title[0] in highlighted_poems_details]
#poets = [poet[1].append() for poet in highlighted_poems_details]
#dates = [date[2].append() for date in highlighted_poems_details]
for title in highlighted_poems_details:
titles.append(title[0])
print(titles)
答案 0 :(得分:2)
正确:
titles = [title[0] for title in highlighted_poems_details]
您没有在理解列表中添加任何内容,而是在定义它。
答案 1 :(得分:1)
使用列表推导时,您必须先在for
之后读取表达式,然后再读取第一部分:
titles = [title[0] for title in highlighted_poems_details]
^------^ ^--------------------------------^
| |
the information iteration over
you want to add your data
to your new list
所以您可以这样阅读:for every title in the poem details, add title[0] to the list
答案 2 :(得分:0)
或使用:
from operator import itemgetter
titles = list(map(itemgetter(0), highlighted_poems_details))
答案 3 :(得分:0)
为什么不起作用?因为您在使用title
时使用的是未定义变量title[0]
,请参见下面的标记
titles = [titles.append(title[0]) for title[0] in highlighted_poems_details]
------------------------^^^^^^^-------^^^^^^^------------------------------
您可以按照Relandom的建议使用
titles = [title[0] for title in highlighted_poems_details]