簡體   English   中英

Python - 將整數列表拆分為正數和負數

[英]Python - Split a list of integers into positive and negative

我正在學習 python,我想知道拆分列表的方法是什么:

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

分成兩個列表,一個包含正整數,另一個包含負整數:

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

您可以使用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]

或者作為一種純粹的功能方法,您還可以使用filter如下:

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]

如果您能負擔得起對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)

我們可以使用一個函數將 +ve 數字和 -ve 數字與單個 for 循環分開

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]
def manipulate_data(alist):
      fo = []
      go = []
      for i in alist:
            if i < 0:
                  fo.append(i)
          #elif(i > 0):
               #    go.append(i)
      print fo
    for i in alist:
            if i > 0:
                  go.append(i)
      print go

def main():
      alist = [54,26,-93,-17,-77,31,44,55,20]
      manipulate_data(alist)

if __name__ == '__main__':
      main()

您也可以在列表理解中使用條件來做到這一點,如下所示:

k = [1, -3, 5, 9, -1, 3, -3, -2]
positive = list()
negative = [i for i in k if i < 0 or (i > 0 and positive.append(i))]

我很確定這是 O(n) 並且這只有兩行。

我們可以使用 lambda 如下:

list(filter(lambda x: 0 > x, A))
Output: [-3, -2, -5, -7]

list(filter(lambda x: 0 <= x, A))
Output: [1, 8, 4, 6]

我們必須將方程 (0 <= x) 更改為 (0 < x) 以避免在正數列表中出現 0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM