迭代列表列表

时间:2016-07-02 19:24:10

标签: loops python-3.x

我的列表如下所示:

['"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

我试图汇总每个类别的数字 - 类别A B C等

到目前为止,已经进行了三天的大多数侧身行动。我真的应该得到一本关于Python的书,因为我刚刚跳进去,现在我在这里问你们。

我知道如何在mysql中执行此操作,但该逻辑在这里没有帮助我。

我的代码:

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

撕掉我的头发,我不会留下很多......

4 个答案:

答案 0 :(得分: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]
]

答案 1 :(得分: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"]应该为您提供类别A的总数。

希望它有助于:)

答案 2 :(得分: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

答案 3 :(得分:0)

如果您正在处理类似字符串的列表,则可以使用ast.literal_eval()函数将字符串计算为元组,然后使用defaultdict()汇总数字:

>>> 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})