【问题标题】:Reassigning values in list重新分配列表中的值
【发布时间】:2021-11-29 21:01:31
【问题描述】:

我正在解决 Kaggle 列表和理解模块,并得到以下代码的错误答案:

def elementwise_greater_than(L, thresh):
    """Return a list with the same length as L, where the value at index i is 
    True if L[i] is greater than thresh, and False otherwise.
    
    >>> elementwise_greater_than([1, 2, 3, 4], 2)
    [False, False, True, True]
    """
    for num in L:
        if L[num] > thresh:
            L[num] = True
        else:
            L[num] = False
    return L
    pass

它给出以下输出:[False, False, 3, True]

if L[num]>thresh 有一个错误,但我不明白是什么。

【问题讨论】:

    标签: python-3.x list


    【解决方案1】:

    在 python 中,in 运算符迭代值而不是键(与 javascript 不同),所以 L[num] 会给你无意义的值。

    尝试获取长度并使用常规 for

    def elementwise_greater_than(L, thresh):
        """Return a list with the same length as L, where the value at index i is 
        True if L[i] is greater than thresh, and False otherwise.
        
        >>> elementwise_greater_than([1, 2, 3, 4], 2)
        [False, False, True, True]
        """
        count = len(L)
        for num in range(0,count):
            if L[num] > thresh:
                L[num] = True
            else:
                L[num] = False
        return L
    

    【讨论】:

    • 感谢in的解释。现在我明白为什么答案很奇怪了
    【解决方案2】:

    首先不要在输入 L 上写,创建一个不同的列表。 其次,当像这样循环时:

    for num in L:
    

    num 是每个位置的值而不是索引。

    代码如下:

    def elementwise_greater_than(L, thresh):
        """Return a list with the same length as L, where the value at index i is 
        True if L[i] is greater than thresh, and False otherwise.
        
        >>> elementwise_greater_than([1, 2, 3, 4], 2)
        [False, False, True, True]
        """
        lst = []
        for num in L:
            if num > thresh:
                lst.append(True)
            else:
                lst.append(False)
        return lst
    

    然后输出:

    [False, False, True, True]
    

    【讨论】:

    • 为什么它使用空列表而不是填充列表?只是对这里的技术感到好奇
    • 它将在填充列表上工作,但覆盖输入不是一个好习惯,而是创建一个空列表并填充它更好。
    猜你喜欢
    • 2018-10-24
    • 2014-12-31
    • 2019-08-19
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2015-10-30
    • 2020-12-26
    相关资源
    最近更新 更多