【问题标题】:How to pass list of pairs to a function from a list comprehension?如何将列表理解中的对列表传递给函数?
【发布时间】:2018-08-24 18:31:30
【问题描述】:

我有一个配对列表:

List_Pairs = [
    ["Eat at Joe's", "Eat my shorts"],
    ["Eat well", "Eat mama's pies"],
     ...]

我有一个函数可以计算一对句子之间的相似度并返回是否超过阈值比率:

def Jaccard_Sim(pair):
    """return Jaccard Similarity Index for similarity between two sentences"""
    ratio = len(set(pair[0][1]).intersection(pair[1])/ 
    float(len(set(pair[0]).union(pair[0][1]))))
    return (ratio > 0.66)

我为我的每一对都叫它:

sim_list = (Jaccard_Sim(pair) for pair in combo_pairs)

...并尝试打印它:

print(list(sim_list))

但我收到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-b9508b63e83f> in <module>()
----> 1 list(sim_list)

<ipython-input-49-8ee7726dd300> in <genexpr>(.0)
----> 1 sim_list = (Jaccard_Sim(pair) for pair in combo_pairs)

<ipython-input-47-f211879c6e96> in Jaccard_Sim(pair)
     12 def Jaccard_Sim(pair):
     13     """return Jaccard Similarity Index for similarity between two sentences"""
---> 14     ratio = len(set(pair[0] 
[1]).intersection(pair[1])/float(len(set(pair[0]).union(pair[0][1]))))
     15     return (ratio > 0.66)
     16 

TypeError: unhashable type: 'list

【问题讨论】:

  • 请同时提供pair 示例,如[SO]: How to create a Minimal, Complete, and Verifiable example (mcve) 中所述。
  • pair[0] 可能是一个列表。你不能做例如set([[1,2]]) 因为列表不可变,因此不可散列
  • @CristiFati 请列出示例,它是对的列表。否则,请澄清。
  • 您应该自下而上构建此逻辑:确保在将 Jacquard 相似度放入函数之前正确计算它。目前,您正在尝试在一组单个字符和一个字符串之间执行交集/联合。
  • 另请注意,您的配对列表不合法。

标签: python list function list-comprehension


【解决方案1】:

集合元素必须是可散列项。列表是可变的,这意味着它不是可散列的。如果您可以简单地切换到元组,那应该可以解决您的哈希问题。

你的计算问题是一个杀手。看你的表情:

ratio = (len(set(pair[0][1]).intersection(pair[1])) /
         float(len(set(pair[0]).union(pair[0][1]))))

pair[0][1] 是单个字符。 pair[0]pair[1] 是字符串。由于一个字符的长度是 1,这个表达式很快就简化为:

1.0 / len(pair[0])

这不完全是 Jaccard 的公式。试试这个:

combo_pairs = [ ['Eat at Joes', 'Eat my shorts'], ['Eat well', 'Eat mamas pies'] ]

def Jaccard_Sim(pair):
    """return Jaccard Similarity Index for similarity between two sentences"""
    chars0 = set(pair[0])
    chars1 = set(pair[1])
    ratio = float(len(chars0.intersection(chars1))) / \
                  len(chars0.union(chars1)) 
    print(chars0, chars1, ratio)
    return (ratio > 0.66)

sim_list = (Jaccard_Sim(pair) for pair in combo_pairs)

print(list(sim_list))

输出:

{'s', 'E', 'o', 'e', 'J', ' ', 't', 'a'} {'s', 'E', 'y', 'r', 'o', ' ', 'h', 't', 'm', 'a'} 0.5
{'E', 'e', ' ', 'l', 't', 'a', 'w'} {'s', 'E', 'p', 'e', ' ', 'i', 't', 'm', 'a'} 0.45454545454545453
[False, False]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多