I'm taking this online Python course而且他们不喜欢学生使用单行解决方案。本课程不接受此解决方案的括号。
我已经用列表理解法解决了这个问题,但是课程拒绝了我的答案。
问题是:
Using
index
and other list methods, write a functionreplace(list, X, Y)
which replaces all occurrences ofX
inlist
withY
. For example, ifL = [3, 1, 4, 1, 5, 9]
thenreplace(L, 1, 7)
would change the contents ofL
to[3, 7, 4, 7, 5, 9]
. To make this exercise a challenge, you are not allowed to use[]
.Note: you don't need to use return.
这是我目前所拥有的,但它由于TypeError而中断:“int”对象是不可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)
对如何解决我的问题有什么想法吗?
如果不允许
enumerate
,也可以使用while
循环。range()
返回整数的平面列表,因此不能将其解压为两个参数。使用enumerate
获取索引元组和值元组:如果不允许使用
enumerate
,请使用普通的旧计数器:最后,您可以使用问题作者可能正在寻找的内容(尽管这是最低效的方法,因为它在每次迭代中都会线性搜索列表):
您也可以尝试(不根据需要使用
[]
s或enumerate()
):这可能不是作业要你做的,但我会把它留在这里学习。
注意:不应该使用
list
作为变量名,因为内置函数已经使用了该名称。我在这里用了l
。相关问题 更多 >
编程相关推荐