2017-04-04 44 views
0

我習慣於Excel,所以我很難考慮如何在Python中這樣做(這不會幫助我是新的編碼)。在Excel中,我會有一列數字,一個字母,一個分類,並且可以很容易地獲得我正在尋找的內容。我嘗試過如何在Excel中鏈接列的方式來搜索列表,但我認爲我的術語/心態已關閉。我有兩個列表,每個元素與另一個元素「鏈接」,例如, A = 2:Python:把一堆列表綁在一起(如Excel列)

[a, b, c, d] 
[2, 7, 5, 6] 

我在另一個文件中另一組列表,categories.txt中:

[‘a’, ‘color’, ‘blue’] 
[‘b’, ‘color’, ‘green’] 
[‘c’, ‘fruit’, ‘apple’] 
[‘d’, ‘color’, ‘blue’] 

我想以某種方式綁在一起,所有這些信息轉換成一種格式,我可以問顏色或藍色,並得到數,也許另一套類似的列表:

輸出(?):

[color, blue, 8] #‘a’ and ‘d’ are added to get 8, since they’re both blue 
[color, green, 7] 
[fruit, apple, 5] 

如果輸出格式很重要,這最終會發送到R,這樣我就可以看到顏色類別(8)中有多少藍色,多少綠色(7)等等。某種形式的字典的工作可能?我已經閱讀了文檔和O'Reilly的詞典部分,但它們看起來並不完全正確。

回答

0

這可能是您的一個選擇。您可以創建一個包含所有信息的對象。您可以像我一樣使用列表,甚至可以標記您傳入的每個屬性,只檢查其中一個屬性。

class ColourGroup: 
    def __init__(self, data): 
     self.data = data 

    def has_item(self, item): 
     if item in self.data: 
      return True 
     else: 
      return False 

colour_groups = [   
    ColourGroup([2, 'a', 'color', 'blue']), 
    ColourGroup([7, 'b', 'color', 'green']), 
    ColourGroup([5, 'c', 'fruit', 'apple']), 
    ColourGroup([6, 'd', 'color', 'blue']), 
] 

def get_colour_group(colour_groups, option): 
    return_groups = [] 
    for colour_group in colour_groups: 
     if colour_group.has_item(option): 
      return_groups.append(colour_group.data) 
    return return_groups 

print(get_colour_group(colour_groups, 'blue')) 
0

首先,得到一個字典是關係列表[a, b, c, d][2, 7, 5, 6]一起使用zip()

alpha_list = [a, b, c, d] 
num_list = [2, 7, 5, 6] 

lookup_dict = dict(zip(alpha_list, num_list)) 

現在,讓我們說你的名單列表存儲如下(假設你有一段代碼解析你的文件到列表中):

from collections import defaultdict 

category_lists = [[‘a’, ‘color’, ‘blue’], [‘b’, ‘color’, ‘green’], [‘c’, ‘fruit’, ‘apple’], [‘d’, ‘color’, ‘blue’]] 

# Lookup the relevant number (from the above dict) for each category list 
# Sum up according to category + color (eg. 'color blue') 
# The below builds up a dictionary like this (for the sample data): 
# { 'color blue': 8, 
# 'color green': 7, 
# 'fruit apple': 5 
# } 
# where from the code, the key into our dict is category_list[1]+' '+category_list[2] 
# eg. 'color blue' 
# and the alphabet code at category_list[0] is looked up using the dict above 
# and added to the running total for 'color blue' 

my_groups = defaultdict(int) 
for category_list in category_lists: 
    my_groups[category_list[1]+' '+category_list[2]] += lookup_dict[category_list[0]] 

# To view your output: 
for key in my_groups: 
    out_list = key.split(' ') 
    out_list.append(my_groups[key]) 
    print out_list 
+0

你能否分解一下這是幹什麼?:對於category_list in category_list : my_groups [category_list [1] +''+ category_list [2]] + = lookup_dict [category_list [0]] – Liquidity

+0

當然,請參閱編輯。 – sgrg

+0

這不符合書面。錯誤在線my_groups = defaultdict(int),它給出語法錯誤 – Liquidity