【发布时间】:2019-12-22 18:02:52
【问题描述】:
我有一个列表列表(称为副本),其中每个列表中的元素(在大列表中)是代表某些电影的字符串(如下所示):
[['history', '1960', 'action'],
['1960', 'western', 'adventure'],
['3d', 'fantasy'],
['agent', 'action', 'adventure'],
....]
其中一些词代表电影类型。我要做的是,对于每个列表,查找流派的单词(通过查看这些单词是否在名为 set_genres 的集合中),将它们放在列表的开头并在其后附加单词“电影” .如果列表中有多个流派,我只想在最后一个流派之后附加“电影”一词。 Set_genres 和所需的输出如下:
set_genres={'action',
'adventure',
'animation',
'comedy',
'crime',
'documentary',
'drama',
'family',
'fantasy',
'foreign',
'history',
'horror',
'music',
'mystery',
'romance',
'science_fiction',
'thriller',
'tv_movie',
'war',
'western'}
#Output
[['history','action movie', '1960'],
['western','adventure movie', '1960'],
['fantasy movie','3d'],
['action', 'adventure movie', 'agent'],
....]
我用来尝试实现此目的的代码如下:
keys=[]
for list_top in copy:
for idx, word in enumerate(list_top):
if word in set_genres:
keys.append((idx,word))
keys.sort(reverse=True)
for idx, word in keys:
del list_top[idx]
for idx, word in keys:
if idx==len(keys)-1:
list_top.insert(0,'{} movie'.format(word))
else:
list_top.insert(0,word)
但是,这不起作用,我无法弄清楚原因。它给了我以下错误:
indexes=[]...
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in
8 keys.sort(reverse=True)
9 for idx, word in keys:
---> 10 del list_top[idx]
11 for idx, word in keys:
12 if idx==len(keys)-1:
IndexError: list assignment index out of range
如果有人知道可能出了什么问题,我会很感激你的帮助!
【问题讨论】:
-
请同时发布与提供的示例输入列表相关的
set_genres示例。 -
不要修改您正在迭代的列表。
-
@anky_91 我在上面添加了!
-
@DanielRoseman 你能告诉我为什么吗?而且,副本已经是原始列表的深度副本
-
@J.Doe,所需输出中的第二项未排序
['western','action movie', '1960']- 这是有意的吗?流派的顺序重要吗?
标签: python string pandas list indexing