简化Python列表理解

简化Python列表理解,python,python-2.7,logic,list-comprehension,Python,Python 2.7,Logic,List Comprehension,有人能简化这段代码背后的逻辑吗 scores=[(similarity(prefs,person,other),other) for other in prefs if other!=person ] 我试着这样实现它 for others in prefs: if others!=person: scores=[similarity(prefs,person, others),others] 但它只选择了其他元素的最后一个元素。 顺便说一句,prefs是一个2D字

有人能简化这段代码背后的逻辑吗

scores=[(similarity(prefs,person,other),other)
for other in prefs if other!=person ]
我试着这样实现它

for others in prefs:
    if others!=person:
        scores=[similarity(prefs,person, others),others] 
但它只选择了其他元素的最后一个元素。
顺便说一句,prefs是一个2D字典,分数应该是元组列表。

这与在列表中重复添加元组相同:

scores = []
for others in prefs:
    if others!=person:
        scores.append((similarity(prefs, person, others), others))

这与在列表中重复添加元组是一样的:

scores = []
for others in prefs:
    if others!=person:
        scores.append((similarity(prefs, person, others), others))

哦,好的,非常感谢。它很好用。我想知道为什么这里使用两个括号会产生不同。当我在append函数中用一对括号尝试时,它给了我一个TypeError。@shonaufded parens将函数调用的返回值和
其他
分组为元组,否则,表达式可能会被认为是不明确的。哦,好的,非常感谢。它很好用。我想知道为什么这里使用两个括号会产生不同。当我在append函数中使用一对括号进行尝试时,它给出了一个TypeError。@shonaufded parens将函数调用的返回值和
其他
分组为元组,否则,表达式可能会被视为不明确。