正在重新分配列表中的值



我正在解决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中,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

首先不要在输入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]

最新更新