2015-04-15 87 views
-1

我有一堆與不同組關聯的項目,我最終要爲每個組創建一個包含所有關聯項目的列表。在Python中動態創建列表

問題是我不知道有多少組,所以我該如何動態生成正確數量的列表以及如何調用它們?

我通過item_listgroup_list,兩個不同的一系列彼此完美allign,如在item_list[item]具有group_list[item]

這裏相應組循環是一些原始數據:

item list group list 
    A    1 
    B    1 
    C    2 
    D    1 
    E    2 
    F    1 
    G    2 
    H    2 
    I    1 
    J    2 

這是我到目前爲止:

groups = [] 

for item in item_list: 
    groups.append(group_list[item]) 

# Get only unique values (instead of having groups 1,1,1,2,2 --> 1,2) 
group_set = list(set(groups)) 

# Number of lists that need to be generated 
len(group_set) 

我想結束爲:

[IN]: print list_1: 
[OUT]: ['A', 'B', 'D', 'F', 'I'] 

[IN]: print list_2: 
[OUT]: ['C', 'E', 'G', 'H', 'J'] 

其中產生LIST_1和list_2因爲LEN(group_set)從我當前的代碼是等於2

我只是不知道如何動態地生成多個列表,並把每個項目在適當的列表中。

任何意見/指導,非常感謝......

+1

你有沒有看着[組](HTTP ://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.groups.html#pandas.core.groupby.GroupBy.groups)?你最終還想做什麼? – EdChum

+0

在這個例子中,如果我們假設我有組1和組2,我希望能夠創建一個包含組1中關聯的所有項目的列表,以及包含組2中關聯項目的另一個列表。但是,如何針對n組?我會調查你提供的這個鏈接,謝謝。 – ploo

+1

好吧,你可以像'df.groupby(col)[other_col] .apply(lambda x:list(x))那樣做' – EdChum

回答

1

你可以使用Python字典理解編譯你想達到...最後兩行的下一個代碼塊做繁重的名單。代碼塊的其餘部分是我將數據轉化爲熊貓。

import pandas as pd 

# get your data into pandas 
data = ''' 
item_list  group_list 
A    1 
B    1 
C    2 
D    1 
E    2 
F    1 
G    2 
H    2 
I    1 
J    2''' 
from StringIO import StringIO # import from io for python 3 
df = pd.read_csv(StringIO(data), sep=r'\s+', index_col=None, header=0) 

# use a dictionary comprehension to compile the collection of lists 
lists = {x: df[df['group_list'] == x].item_list.tolist() 
    for x in df['group_list'].unique()} 

這給了我在IPython中執行以下操作:

In [27]: print(lists) 
{1: ['A', 'B', 'D', 'F', 'I'], 2: ['C', 'E', 'G', 'H', 'J']} 

In [28]: print(lists[1]) 
['A', 'B', 'D', 'F', 'I'] 

In [29]: print(lists[2]) 
['C', 'E', 'G', 'H', 'J'] 
+0

嗨馬克,這是一個很棒的解決方案,謝謝! 'tolist()'和'unique()'是完美的,尤其是unique(),比將列表轉換爲集合並返回列表更清晰。 – ploo

1

或者你可以做這樣的事情@EdChum以上建議...

In [11]: x = df.groupby('group_list')['item_list'].apply(lambda x: x.tolist()) 

In [12]: print(x) 
group_list 
1 [A, B, D, F, I] 
2 [C, E, G, H, J] 
Name: item_list, dtype: object 

In [13]: print(x[1]) 
['A', 'B', 'D', 'F', 'I'] 

In [14]: print(x[2]) 
['C', 'E', 'G', 'H', 'J']