三行代码  ›  专栏  ›  技术社区  ›  Michael

在列表中重新指定值

  •  0
  • Michael  · 技术社区  · 1 月前

    我正在解决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 但我不明白是什么。

    2 回复  |  直到 1 月前
        1
  •  1
  •   hirad davari    1 月前

    在python中,In操作符迭代值而不是键(与javascript相反),因此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]
        """
        count = len(L)
        for num in range(0,count):
            if L[num] > thresh:
                L[num] = True
            else:
                L[num] = False
        return L
    
        2
  •  1
  •   RoseGod    1 月前

    首先不要写在输入L上,创建一个不同的列表。

    for num in L:
    

    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]