我正在学习这个在线 Python 课程,他们不喜欢学生使用单线解决方案。本课程不接受此解决方案的括号。
我已经使用列表理解解决了这个问题,但是课程拒绝了我的回答。
问题如下:
使用
index
和其他列表方法,编写一个函数replace(list, X, Y)
,将所有出现的X
inlist
替换为Y
。例如,如果L = [3, 1, 4, 1, 5, 9]
thenreplace(L, 1, 7)
将更改L
to的内容[3, 7, 4, 7, 5, 9]
。为了使这个练习成为一个挑战,你不能使用[]
.注意:你不需要使用return。
这是我到目前为止所拥有的,但由于 TypeError: 'int' object is not iterable 而中断。
list = [3, 1, 4, 1, 5, 9]
def replace(list, X, Y):
while X in list:
for i,v in range(len(list)):
if v==1:
list.remove(1)
list.insert(i, 7)
replace(list, 1, 7)
这是我最初的答案,但被拒绝了。
list = [3, 1, 4, 1, 5, 9]
def replace(list, X, Y):
print([Y if v == X else v for v in list])
replace(list, 1, 7)
关于如何解决我更长的解决方案的任何想法?