在两个列表中偏移正数和负数,然后在Python中获得其余数字

发布于 2025-01-24 09:44:59 字数 267 浏览 0 评论 0原文

我有两个列表,包括一系列正数或负数,两个列表可能具有不等的长度,例如:

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]

在两个列表中具有同样绝对值的正数和负数,被数量抵消,有什么简单的方法吗?

I have two lists consisting of a series of positive or negative numbers, and two lists may have unequal lengths, like this:

lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]

The result I want to get is:

lst_ofs = [-1, -2, 3, 5, 6, 6, 8, -11]

Positive and negative numbers with equal absolute value in the two lists are offset by quantity, is there any easy way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我最亲爱的 2025-01-31 09:44:59

该解决方案将每个数字的正和负实例的数量计算为最大值。必要时在每次迭代上扩展输出列表。

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]

This solution counts the number of the positive and negative instances of each number up to the maximum. The output list is extended on each iteration as necessary.

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)

Output:

[-1, -2, 3, 5, 6, 6, 8, -11]
醉南桥 2025-01-31 09:44:59
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

这不是最有效的解决方案,因为循环的每次删除两个值时启动。但这应该起作用。

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

This isn't the most efficient solution, because the for loop starts over each time two values are removed. But it should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文