[英]How can I sum pairs of numbers in a list and if the sum is equal to another element in the list, how can I remove this element from the list?
我有一个数字列表:
nums = [-3,-2,-1,1,2,3,0,0]
而我想遍历列表, add two numbers at a time
,如果这两个数字的sum
是列表中的一个元素(不包括我们刚刚求和的两个),那么我想remove the element
。 我怎样才能做到这一点?
例如, since -3+2= -1
并且-1 is in the list
,我可以从列表中删除 -1。
我试图创建一个空list/set
来存储每对元素的总和,然后将 nums 中的元素与这个list/set
进行比较,但这不起作用,因为它违反了我想做的第二部分- in brackets above
!
PS 我想remove as many elements as possible
,并且担心如果我在迭代列表时删除元素 - 在找到所有对和之前 - 那么我可能会错过一些有效的对和!
任何帮助深表感谢。
虽然可能效率低下(写这个答案时不关心效率),但您可能会执行以下操作:
for first in nums[:]:
if first == 0: continue
for second in nums[:]:
if second == 0: continue
sum = first + second
if sum in nums:
nums.remove(sum)
go 在这个答案中我将完成两件事;
nums[:]
是切片语法,它只会创建数组的一个副本,之后将迭代该副本。 在此答案中找到了此语法: https://stackoverflow.com/a/1207461/6586516n - 1
数字等于 0 时,一组数字的总和才能等于其自身/加法中使用的数字中的一个(其中 n 是加法中使用的数字的数量)你可以尝试这样的事情:
itertools.combinations
返回给我们所有可能的参数组合。 因为你想要数字,提供2
作为参数将返回所有可能的长度为 2 的组合
然后我们将检查条件并继续从列表中删除。
from itertools import combinations
nums = [-3,-2,-1,1,2,3,0,0]
nums2=[i for i in combinations(nums,2)]
print(nums2)
for i in nums2:
sums=i[0]+i[1]
if sums in nums and (sums!=i[0] and sums!=i[1]):
try:
print(f"{sums} removed from list.\nNew List: {nums}")
nums.remove(sums)
except ValueError:
print("{sums} not in list")
print(nums)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.