【问题标题】:How to extract the minimum position of a string in a nested list如何提取嵌套列表中字符串的最小位置
【发布时间】: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


【解决方案1】:

一种方法是通过简单的for 循环构造一个将单词映射到索引的字典,前提是字典中不存在该单词。然后使用map提取uniquewords中每个单词的索引。

d = {}
for idx, (word, _) in enumerate(words):
    if word not in d:
        d[word] = idx

res = list(map(d.__getitem__, uniquewords))

print(res)

[0, 3, 5, 6]

【讨论】:

    【解决方案2】:

    根据我的评论:

    # dictionary comprehension... make an empty list entry for each word
    k = {word[0]:list() for word in words}
    # iterate through the list appending the word occurrence list entries
    for word in words:
        k[word[0]].append(word[1])
    

    【讨论】:

    • 我试图破译这是如何获得[0, 3, 5, 6] 但失败了。你能举个例子吗?
    • 哦,不会的!我完全误解了这个问题。感谢您指出这一点,@jpp
    • @mburling 是的,这不能回答问题,但我可以问第一行 - k = {word[0]:list() for word in words} 如何获得唯一单词? (我知道有,我想知道怎么做)
    • @song0089 这是一个创建字典的惰性单行器。这等效于创建一个空字典并为我们正在遍历解析为空列表的单词列表的每个元素插入一个键。字典强制唯一性。
    【解决方案3】:

    由于这个列表的格式,我们可以使用itertools.groupby,并为groupby(words, key=lambda x: x[0])抓取list(g)中第一项的索引

    res = [words.index(list(g)[0]) for k, g in groupby(words, key=lambda x: x[0])]
    

    扩展:

    res = []
    for k, g in groupby(words, key=lambda x: x[0]):
        res.append(words.index(list(g)[0]))
    
    print(res)
    # [0, 3, 5, 6]
    

    此外,我们可以在子列表中搜索我们唯一的单词并获取索引然后中断。这将阻止循环为每个关键字获取更多索引。

    res = []
    for i in uniquewords:
        for j in words:
            if i in j:
                res.append(words.index(j))
                break
    print(res)
    # [0, 3, 5, 6]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2012-03-11
      • 2016-02-08
      • 2022-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多