我正在尝试遍历列表nums
,每次删除其元素之一(例如x
)。
我无法使用list.remove(x)
来做到这一点,因为这是不可迭代的。
如果我要进行另一个列表理解[n for n in nums if n != x]
,这将删除所有与'y'
匹配的元素,而不仅仅是第一个。
因此,我使用nums[:nums.index(x)]+nums[nums.index(x)+1:]
是否有更漂亮或更有效的方法?
出于其他背景,我在处理列表理解表达式时开始考虑这一点(我确定这本身并不是最高效的代码):
[x for x in nums if target - x in nums[:nums.index(x)]+nums[nums.index(x)+1:]]