在没有列表理解、切片或使用[]s的情况下替换列表中的元素

2024-05-13 23:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

I'm taking this online Python course而且他们不喜欢学生使用单行解决方案。本课程不接受此解决方案的括号。

我已经用列表理解法解决了这个问题,但是课程拒绝了我的答案。

问题是:

Using index and other list methods, write a function replace(list, X, Y) which replaces all occurrences of X in list with Y. For example, if L = [3, 1, 4, 1, 5, 9] then replace(L, 1, 7) would change the contents of L 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)

对如何解决我的问题有什么想法吗?


Tags: oftoinyouforifusedef
3条回答

如果不允许enumerate,也可以使用while循环。

>>> def replace(L_in, old_v, new_v):
        while old_v in L_in:
            idx=L_in.index(old_v)
            L_in.pop(idx)
            L_in.insert(idx, new_v)


>>> L = [3, 1, 4, 1, 5, 9]
>>> replace(L, 1, 7)
>>> L
[3, 7, 4, 7, 5, 9]

range()返回整数的平面列表,因此不能将其解压为两个参数。使用enumerate获取索引元组和值元组:

def replace(l, X, Y):
  for i,v in enumerate(l):
     if v == X:
        l.pop(i)
        l.insert(i, Y)

l = [3, 1, 4, 1, 5, 9]
replace(l, 1, 7)

如果不允许使用enumerate,请使用普通的旧计数器:

def replace(l, X, Y):
  i = 0
  for v in l:
     if v == X:
        l.pop(i)
        l.insert(i, Y)
     i += 1

l = [3, 1, 4, 1, 5, 9]
replace(list, 1, 7)

最后,您可以使用问题作者可能正在寻找的内容(尽管这是最低效的方法,因为它在每次迭代中都会线性搜索列表):

def replace(l, X, Y):
  for v in l:
     i = l.index(v)
     if v == X:
        l.pop(i)
        l.insert(i, Y)

l = [3, 1, 4, 1, 5, 9]
replace(l, 1, 7)

您也可以尝试(不根据需要使用[]s或enumerate()):

for i in range(len(l)):  # loop over indices
    if l.__index__(i) == X:  # i.e. l[i] == X
        l.__setitem__(i, Y)  # i.e. l[i] = Y

这可能不是作业要你做的,但我会把它留在这里学习。

注意:不应该使用list作为变量名,因为内置函数已经使用了该名称。我在这里用了l

相关问题 更多 >