将两个列表中的正数和负数偏移并在 Python 中获取其余部分
Offset positive and negative numbers in two lists and get the rest in Python
我有两个列表,由一系列正数或负数组成,两个列表的长度可能不等,像这样:
lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]
我想要得到的结果是:
lst_ofs = [-1, -2, 3, 5, 6, 6, 8, -11]
两个列表中绝对值相等的正负数按数量抵消,有什么简单的方法吗?
result = lst1 + lst2
# keep checking for pairs until none are left
while True:
for v in result:
if -v in result:
# if v and -v are in the list, remove them both
# and restart the for loop
result.remove(v)
result.remove(-v)
break
else:
# if the for loop made it all the way to the end,
# break the outer loop
break
这不是最有效的解决方案,因为每次删除两个值时 for
循环都会重新开始。但它应该有效。
本解法统计每个数字的正例和负例的个数,直到最大值。根据需要在每次迭代中扩展输出列表。
lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]
lst_ofs = []
for i in range(max(max(lst1), -min(lst2)) + 1):
n = lst1.count(i) - lst2.count(-i)
if abs(n) > 0:
lst_ofs.extend([int(i * n / abs(n))] * abs(n))
print(lst_ofs)
输出:
[-1, -2, 3, 5, 6, 6, 8, -11]
我有两个列表,由一系列正数或负数组成,两个列表的长度可能不等,像这样:
lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]
我想要得到的结果是:
lst_ofs = [-1, -2, 3, 5, 6, 6, 8, -11]
两个列表中绝对值相等的正负数按数量抵消,有什么简单的方法吗?
result = lst1 + lst2
# keep checking for pairs until none are left
while True:
for v in result:
if -v in result:
# if v and -v are in the list, remove them both
# and restart the for loop
result.remove(v)
result.remove(-v)
break
else:
# if the for loop made it all the way to the end,
# break the outer loop
break
这不是最有效的解决方案,因为每次删除两个值时 for
循环都会重新开始。但它应该有效。
本解法统计每个数字的正例和负例的个数,直到最大值。根据需要在每次迭代中扩展输出列表。
lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]
lst_ofs = []
for i in range(max(max(lst1), -min(lst2)) + 1):
n = lst1.count(i) - lst2.count(-i)
if abs(n) > 0:
lst_ofs.extend([int(i * n / abs(n))] * abs(n))
print(lst_ofs)
输出:
[-1, -2, 3, 5, 6, 6, 8, -11]