如何创建循环遍历另一个列表中的整数的列表索引

时间:2016-01-21 04:46:41

标签: python list indexing

我有这个清单:

sentences = ['The number of adults who read at least one novel within the past 12 months fell to 47%.', 
'Fiction reading rose from 2002 to 2008.', 'The decline in fiction reading last year occurred mostly among men.', 
'Women read more fiction.', '50% more.', 'Though it decreased 10% over the last decade.', 'Men are more likely to read nonfiction.', 
'Young adults are more likely to read fiction.', 'Just 54% of Americans cracked open a book of  any kind last year.', 
'But novels have suffered more than nonfiction.']

我还有另一个列表,其中包含上面列表中包含数字的所有句子序列的索引。

index_groupings = [[0, 1], [4, 5], [8]]

我想通过使用变量“index_groupings”中的索引在变量“sentences”中提取指定的句子序列,以便得到以下输出:

在过去12个月内读过至少一本小说的成年人数下降至47%。从2002年到2008年,读书数量有所上升。

增加50%。虽然它在过去十年中下降了10%。

去年,只有54%的美国人破解了任何一本书。

所以我做了以下事情:

for grouping in index_groupings:
    if len(grouping) > 1:
        print sentences[grouping[:]]
    else:
        print sentences[grouping[0]]

当我运行时,我收到一条错误消息,上面写着

TypeError: list indices must be integers, not list

print sentences[grouping[:]]行将其绊倒。有没有办法循环遍历index_groupings列表中的索引序列,以便返回正确的输出?

2 个答案:

答案 0 :(得分:0)

print ["".join(map(lambda x:sentences[x],i)) for i in index_groupings]

您可以使用joinlist comprehension。这里。

输出:['The number of adults who read at least one novel within the past 12 months fell to 47%. Fiction reading rose from 2002 to 2008.', '50% more. Though it decreased 10% over the last decade.', 'Just 54% of Americans cracked open a book of any kind last year.']

答案 1 :(得分:0)

Python为此提供了一些电池:

for grouping in index_groupings:
    if len(grouping) > 1:
        print sentences[slice(*grouping)]
    else:
        print sentences[grouping[0]]

slice构造函数在a[x:y:z]时被使用(它被转换为a[slice(x, y, z)],除了使用专门的字节代码来避免一些开销之外),这只是创建一个显式,因为我们有调用构造函数所需的值序列,并且它比索引或解包然后使用切片语法更方便。