所以我现在正在解决这个问题:https://www.codewars.com/kata/5279f6fe5ab7f447890006a7/train/python
但本质上,我唯一的问题是,当循环遍历数据时,我希望将字符串(索引)“10”作为值添加到键“pos”,但正如您所看到的,它添加了“1”,“0”而不是“10”。
例如,如果我将数组中的值6更改为12->,也会发生同样的情况; 它应该是“%1”,“%2”,而不是12。
有人能告诉我怎么修吗?
def pick_peaks(data):
answer = {'pos': [], 'peaks': []}
for index, value in enumerate(data):
if index == 0 or index == len(data)-1:
pass
elif data[index-1] < value and data[index+1] < value:
answer['pos'] += str(index)
answer['peaks'] += str(data[index])
elif data[index] > data[index-1] and max(data[index:]) == data[index]:
answer['pos'] += str(index)
answer['peaks'] += str(data[index])
return answer
print(pick_peaks([8, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 2, 2, 1]))
Output: {'pos': ['3', '7', '1', '0'], 'peaks': ['6', '3', '2']}
+=
与list.extend
相同,这意味着字符串被视为可迭代字符串,每个字符都被添加到列表中。 您打算使用list.append
:
answer['pos'].append(str(index))
answer['peaks'].append(str(data[index]))
或者您可能打算执行+=[]
,但list.append
更合适。
请参阅文档:可变序列类型
还要注意,Codewars challenge要求的是int列表,而不是字符串,如果您尝试用int扩展列表,您会得到一个错误:
>>> [].extend(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable