【发布时间】:2019-03-14 18:58:47
【问题描述】:
我有一个包含大量重复项的 words 嵌套列表,以及一个 uniquewords 列表,它是列表 words 的集合。我想在word中找到一个项目的最小起点。例如:
words = [['apple',5],['apple',7],['apple',8],['pear',9], ['pear',4]
['grape',6],['baby',3],['baby',2],['baby',87]]
uniquewords = ['apple','pear','grape','baby']
我想要一个最终结果:
[0,3,5,6]
我尝试使用enumerate(),因为index() 不适用于嵌套列表。
a = []
>>> for i in range(len(uniquewords)):
... for index,sublist in enumerate(words):
... if uniquewords[i] in sublist:
... a.append(min(index))
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: 'int' object is not iterable
我感觉这不起作用,因为我没有告诉 python 为每个唯一词附加索引。我怎么去那里?
【问题讨论】:
-
我开始在列表格式的列表中解决这个问题,最后我将内容转换为字典......在我看来,如果你使用字典,比如说,将您的标记映射到它们的出现列表,您将有更好的时间。
k = { 'apple': [5, 7, 8]}和min(k['apple'])将是一个很好的替代品。想法?
标签: python list enumerate python-3.7