2015-11-21 38 views
1

您好我試着走的每子表的不同項目,並形成陣列蟒蛇numpy的解析陣列來獲得項目

我的輸入是一個二維表

alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']] 

和輸出我要的是不同項目的數組

out = [1,2,3,5,15,657] 

我試圖

from numpy import np 

alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']] 
anarray = np.array(alist) 
newarray = [] 
for i in anarray: 
     for j in i: 
      if j in newarray: 
       pass 
      else: 
       print j 
+0

你想採取哪些獨特的元素?有沒有規則? – pythad

+0

如果你不關心你可以使用列表(集(sum(alist,[]))) –

+0

@pythad我想存儲結果數組進行進一步操作 – Kristy

回答

0

你可以利用一組:

out = set() 

for inner in alist: 
    out.update(inner) 

out = map(int, out) # in your example you have a list of ints 

>>> print out 
[1, 2, 3, 5, 15, 657] 
0
from itertools import chain 

alist = [['1', '2'], ['3', '5', '2'], ['15', '1'], ['5', '657', '3', '1']] 

# Flatten the list into a single-level list of all the values 
flattened_list = list(chain.from_iterable(alist)) 

# Use a set to remove the duplicates 
uniques = set(flattened_list) 

# Sort the unique values by the numeric value of each value 
sorted_results = sorted(uniques, key=lambda value: int(value)) 

print sorted_results 
0

修改你的代碼稍微您可以將結果保存在newarray:

alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']] 
newarray = [] 
for i in alist: 
    for j in i: 
     if j in newarray: 
       pass 
     else: 
       newarray.append(j) 

你的結果將被存儲在newarray

爲了讓它稍微好一點:

alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']] 
newarray = [] 
for i in alist: 
    for j in i: 
     if j not in newarray: 
       newarray.append(j)