Python将整数列表分成正整数和负整数

2024-04-18 23:58:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python,我想知道如何分割一个列表,比如:

A = [1, -3, -2, 8, 4, -5, 6, -7]

分成两个列表,一个包含正整数,另一个包含负整数:

B = [1, 8, 4, 6]
C = [-3, -2, -5, -7]

Tags: 列表整数正整数
1条回答
网友
1楼 · 发布于 2024-04-18 23:58:43

如果您能负担得起两次迭代A,那么列表理解在IMO中是最好的:

B = [x for x in A if x >= 0]
C = [x for x in A if x < 0]

当然总有“手册”的方法:

A = [1, -3, -2, 8, 4, -5, 6, -7]
B = []
C = []
for x in A:
    if (x >= 0):
        B.append(x)
    else:
        C.append(x)
网友
2楼 · 发布于 2024-04-18 23:58:43

我们可以使用一个函数用一个for循环来分离+ve数字和-ve数字

def separate_plus_minus(numbers_list):
    positive = []
    negative = []
    for number in numbers_list:
        if number >= 0:
             positive.append(number)
        else:
             negative.append(number)
    return positive, negative

使用:

numbers_list = [-1,5,6,-23,55,0,25,-10]
positive, negative = separate_plus_minus(numbers_list)

输出:

positve = [5, 6, 55, 0, 25]
negative = [-1, -23, -10]
网友
3楼 · 发布于 2024-04-18 23:58:43

您可以使用defaultdict()在O(n)中执行此操作:

In [3]: from collections import defaultdict

In [4]: d = defaultdict(list)

In [5]: for num in A:
   ...:     if num < 0:
   ...:         d['neg'].append(num)
   ...:     else: # This will also append zero to the positive list, you can change the behavior by modifying the conditions 
   ...:         d['pos'].append(num)
   ...:         

In [6]: d
Out[6]: defaultdict(<class 'list'>, {'neg': [-3, -2, -5, -7], 'pos': [1, 8, 4, 6]})

另一种方法是使用两个单独的列表理解(不推荐用于长列表):

>>> B,C=[i for i in A if i<0 ],[j for j in A if j>0]
>>> B
[-3, -2, -5, -7]
>>> C
[1, 8, 4, 6]

或者使用^{}函数:

In [19]: list(filter((0).__lt__,A))
Out[19]: [1, 8, 4, 6]

In [20]: list(filter((0).__gt__,A))
Out[20]: [-3, -2, -5, -7]

相关问题 更多 >