2016-07-02 38 views
0

のリストの上に私のリストは、次のようになります。反復処理リスト

['"date","supermarket","categoryA",10', 
'"date","candy store","categoryB",5', 
'"date","drugstore","categoryC",6', 
'"date","supermarket","categoryA",20', 
'"date","candy store","categoryB",2', 
'"date","drugstore","categoryC",90'] 
etc 

私はカテゴリごとの数字を集計しようとしている - categoryA BCなど

これまでのところ、それは3日となっています主に横の動きの私はちょうど飛び込んだので、私は本当にPythonに関する本を手に入れなければなりません。そしてここで私は皆さんにお尋ねします。

私はこれをmysqlで行う方法を知っていますが、そのロジックはここで私を助けてくれません。

マイコード:

for x in range(0 , len(list)): 
    for y in list[x][2]: 
     value += list[x][3] 

+3

私はリストのリストを表示しません。リストは1つだけですが、間違えましたか? –

+0

あなたがここに貼り付けた「リスト」は、その中にちょうど1つの要素(文字列)を持つリストです。あなたの実際の入力がどのように見えるかを明確にすることができますか? – smarx

+0

申し訳ありませんが、間にコンマがあると思います – MerynDH

答えて

0

使用辞書はinを使用して集約し、反復リストを保持するために...私の毛を引き裂く、と私は左のそれらの多くはありません。

上記のリストのリストを想定してい
aggregate = {} 
for x in list: 
    if (x[2] not in aggregate): 
     aggregate[x[2]] = 0 
    aggregate[x[2]] += x[3] 

は次のようになります。

[ 
    ["date","supermarket","categoryA",10], 
    ["date","candy store","categoryB",5] 
] 
+0

@krzyk提案した入力に対してコードがどのように機能するかわかりません。 (それぞれの内部リストには要素が1つしかないので、 'x [2]'や 'x [3]'を使ったときにおそらく 'IndexError'が出ます。) – smarx

+0

@smarxはい、貼り付けをあまりにも多くコピーしましたが、私は ''を削除しました –

0

Python辞書を使用すると、多くのことが簡単になります。これは動作します:

最後に
category_aggregate_dictionary = {} 
for x in range(0 , len(list)): 
    for y in list[x][2]: 
     value = list[x][3] 
     category_aggregate_dictionary[y] = 0 if category_aggregate_dictionary.get(y, None) == None 
    category_aggregate_dictionary[y] += float(value) 

category_aggregate_dictionary["categoryA"]はあなたにcategoryAの総数を与える必要があります。

希望するもの:)

+0

@smarxで述べたように、これはカンマで区切られた文字列のリストではなく、実際にリストのリストを持っていることを前提としています。 –

0

ここでは実際にリストのリストがあると仮定しています。 (以下「エントリー」のための私の値を参照してください。)

from collections import Counter 

entries = [ 
    ["date", "supermarket", "categoryA", 10], 
    ["date", "candy store", "categoryB", 5], 
    ["date", "drugstore", "categoryC", 6], 
    ["date", "supermarket", "categoryA", 20], 
    ["date", "candy store", "categoryB", 2], 
    ["date", "drugstore", "categoryC", 90] 
] 

# A Counter is much like a dictionary with a default value of 0 
category_counts = Counter() 

for entry in entries: 
    category = entry[2] 
    count = entry[3] 
    category_counts[category] += count 

# You have the counts already at this point. This loop will 
# just print them out in sorted order (by category name).  
for category in sorted(category_counts.keys()): 
    print('{}: {}'.format(category, category_counts[category])) 

# Output: 
# categoryA: 30 
# categoryB: 7 
# categoryC: 96 
0

タプルは、その後の数字を集約するdefaultdict()を使用すると、あなたの文字列を評価するためにast.literal_eval()機能を使用できるようにあなたは、文字列のリストを扱っている場合:

>>> from collections import defaultdict 
>>> from ast import literal_eval 
>>> d = defaultdict(int) 
>>> for item in lst: 
...  *_, cat, num = literal_eval(item) 
...  d[cat]+=num 
... 
>>> d 
defaultdict(<class 'int'>, {'9': 0, 'categoryA': 30, 'categoryC': 96, 'categoryB': 7})