我想从数组中删除值x
,我有以下约束:
所以
a = [1, 2, 'x', 3, 4, 5]
变成
^{pr2}$只有一个x
的情况很简单,我只将所有内容左移一个位置:
def removeSingleElement(value, array):
i = 0
while i < len(array)-1:
if array[i] == value:
for val in array[i:-1]:
array[i] = array[i+1]
i += 1
else:
i += 1
array[-1] = None
return array
但是我如何处理一个具有重复值的数组呢?在
a = [1, 'x', 2, 3, 'x', 4]
应该变成
a = [1, 2, 3, 4, None, None]
(我的想法是,我不能调整数组的大小,所以我想向左移动所有内容,并用Null
的值填充其余的内容)。在
免责声明:这不是一个Python问题,我在寻找一般的算法,碰巧我发现Python很方便表达这个想法;)
代码:
输出:
^{pr2}$假设允许您预先知道数组的长度并存储一个计数器,则可以执行以下操作:
你需要两个索引,一个用于阅读和写作:
相关问题 更多 >
编程相关推荐