我想从给定的项目列表中进行配对。我在python中使用来自 itertools 的组合
def call_jaccard(listOfItems):
returnList = []
if (len(listOfItems) >= 2):
returnList.append(list(combinations(listOfItems, 2)))
return returnList
然而,我得到的输出是:
[[(u'U3', u'U8')]], [], [], [], [], [[(u'U9', u'U10'), (u'U9', u'U2'), (u'U10', u'U2')]], [], [], [], [], [], [[(u'U3', u'U8')]], [], [], [], [], [], [], [], [], [[(u'U9', u'U10'), (u'U9', u'U2'), (u'U10', u'U2')]], [], [], [], [[(u'U9', u'U2')]], [], [], [], [[(u'U3', u'U8')]], [[(u'U3', u'U8')]], [], [], [], [], [], [[(u'U3', u'U8')]], [], [], [], [[(u'U9', u'U2')]], [[(u'U9', u'U10'), (u'U9', u'U2'), (u'U10', u'U2')]], []]
如何摆脱这些额外的[]?
我还尝试检查我追加的项目是否为空,如下所示:
def call_jaccard(listOfItems):
returnList = []
if (len(listOfItems) >= 2):
for x in (list(combinations(listOfItems, 2))):
if len(x) >0:
returnList.append(x)
但仍然得到相同的空[]。请帮忙!
listOfItems将包含一个列表:
[1,2,3] or [1] or [1,2]
预期输出是上述的组合。如果是单项,则应忽略。
答案 0 :(得分:0)
我相信你要找的是
def call_jaccard(listOfItems):
if len(listOfItems) < 2:
return []
return [list(i) for i in combinations(listOfItems, 2)]
itertools.combinations
迭代你想要的对的元组。要将每个对和外部集合转换为列表,您需要明确地转换它们。
call_jaccard([1,2,3])
>>> [[1, 2], [1, 3], [2, 3]]