【问题标题】:Simplifying Python List Comprehension简化 Python 列表理解
【发布时间】:2017-07-26 13:23:37
【问题描述】:

谁能简化这段代码背后的逻辑:

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 字典,而 score 应该是一个元组列表。

【问题讨论】:

    标签: python python-2.7 logic list-comprehension


    【解决方案1】:

    这与将元组重复追加到一个列表中是一样的:

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

    【讨论】:

    • 哦,好的,非常感谢。它工作正常。我想知道为什么在这里应用两个括号会有所不同。当我用一对括号来尝试 append 函数时,它给了我一个 TypeError。
    • @ShonAufdaded 括号将函数调用的返回值和others 分组为一个元组,否则,表达式可能被认为是不明确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多