【问题标题】:Problems computing a score of two lists in python?在 python 中计算两个列表的分数时出现问题?
【发布时间】:2015-05-06 17:44:52
【问题描述】:

假设我有两个列表,两个列表具有相同数量的元素(子列表):

list_1 = [['Hi my name is anon'],
                 ['Hi I like #hokey'],
                 ['Hi I like hokey'],
                 ['Hello guys'],
                 .....
                 ['Thanks for the help']]


list_2 = [['Hi my name is anon_2'],
                 ['Hi I like #Basketball'],
                 ['Hi I like hokey'],
                 ['Hello guys'],
                 ....
                 ['Thanks for the support']]

我想计算list_1 的第一个子列表和list_2 的第一个子列表之间的distance,依此类推,直到 n-1 并将分数放在一个新列表中(即在这个方式:从list_1sublist_1 与从list_2sublist_1 等等直到 n-1)

这是我尝试过的,带有地图:

import distance as dis

scores_list = list(set(map(dis.jaccard(list_of_lists_1,list_of_lists_2) )))
print scores_list

但是得到这个回溯:

test.py
Traceback (most recent call last):
  File "test.py", line 19, in <module>
    scores_list = set(map(dis.jaccard(list_of_lists_1,list_of_lists_2) ))
  File "test.py", line 33, in jaccard
    set1, set2 = set(seq1), set(seq2)
TypeError: unhashable type: 'list'

Process finished with exit code 1

我想要一个这样的列表:

scores_list = [score_1, score_2,score_3,score_4,score_5]

【问题讨论】:

  • dis.jaccard 有问题。您正在尝试从多维集合创建一个集合。最好阅读 python 文档中的“set”。

标签: python list python-2.7 data-structures


【解决方案1】:

问题是你有一个字符串列表。要摆脱内部列表,您可以使用 lambda

strings_1 = [i[0] for i in list_1]
strings_2 = [i[0] for i in list_2]

编辑:

如果你想比较每对字符串,你会这样做

scores_list = [dis.jaccard(i,j) for i,j in zip(strings_1, strings_2)]

我更喜欢上面的列表理解,但如果你确实想使用map,你会使用这样的东西

scores_list = list(map(dis.jaccard, zip(strings_1, strings_2)))

【讨论】:

  • 感谢您的帮助。我得到了这个踪迹:, line 24, in &lt;module&gt; scores_list = list(set(map(dis.jaccard(strings_1, strings_2)))) TypeError: map() requires at least two args 此外,我想比较list_1list_2子列表,而不是两者(即不是list_1 和list_2 作为一个整体)
  • @skwoi 我想我得到了你想要的东西,如果那是你所追求的,请查看我的编辑
【解决方案2】:

您可以通过zip 使用列表推导

scores_list = [dis.jaccard(val1[0], val2[0]) for val1, val2 in zip(list_1, list_2)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2021-07-04
    • 1970-01-01
    • 2017-03-08
    相关资源
    最近更新 更多