我有一个L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]
形式的列表,我想删除发生1的第三个索引,并将其替换为0.我的代码就是这个,但这会删除以前的索引1(第1和第2也)我想在我的名单中。我的代码就是这个
counter=0
index = 2
L = list([1, 2, 3, 4, 1, 2, 1, 3, 0, 4])
print("Value before is\n", L)
for i in range(len(L)):
y=L.index(1)
print(y)
if(counter==index):
L[y]=0
break
else:
counter=counter+1
L[y]
print("Value of list in else\n",L)
print("Value of counter\n",counter)
print("After the value is\n",L)
因此输出为
[2, 3, 4, 2, 0, 3, 0, 4]
但我希望它为
L = [1, 2, 3, 4, 1, 2, 0, 3, 0, 4]
并记住我不会直接给出我想要更改的索引
所以我可以做L[7]=0
提前致谢
答案 0 :(得分:3)
使用enumerate
<强>演示:强>
index = 2
value = 1
c = 0
L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]
for i, v in enumerate(L):
if v == value:
if c == index:
L[i] = 0
break
else:
c+=1
print( L )
<强>输出:强>
[1, 2, 3, 4, 1, 2, 0, 3, 0, 4]
答案 1 :(得分:3)
您的算法存在一些问题,但归结为:通过y = L.index(1)
,您可以找到1
出现的第一个索引。因此,通过执行L[y] = 0
,您所能做的就是更新1
的第一次出现。
找不到 nth 外观没有构建,因此您必须编写它。
为了与list.index
保持一致,我发现以下index
函数在找不到该项时会引发ValueError
。
def index(lst, obj, n=1):
count = 0
for index, item in enumerate(lst):
if item == obj:
count += 1
if count == n:
return index
raise ValueError('{} is not in list at least {} times'.format(obj, n))
L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]
index = index(L, 1, n=3)
L[index] = 0
print(L)
[1, 2, 3, 4, 1, 2, 0, 3, 0, 4]
或者,如果您要做的只是替换 nth 出现,但不关心其实际索引,您可以生成一个包含列表推导和{{1}的新列表对象。
itertools.count
from itertools import count
def replace(lst, obj, repl, n=1):
counter = count(1)
return [repl if x == obj and next(counter) == n else x for x in lst]
L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]
new_list = replace(L, 1, 0, n=3)
print(new_list)
答案 2 :(得分:1)
您可以设置一个名为timesOccured
的计数器变量,用于列表中出现整数1
的次数。
timesOccured == 3 and L[i] == 1
后,您可以像L[i]
那样交换0
的值,如下所示:
if timesOccured == 3 and L[i] == 1:
L[i] = 0
我还建议删除counter
变量,除非你的程序的另一部分需要它。 range
中的for i in range(L)
函数返回一个包含L
所有索引的列表。在这种情况下,range(L)
会返回[0,1,2,3,4,5,6,7,8,9]
。然后for
循环遍历此列表,在i
中分配当前迭代索引中存储的当前值。