I wonder how to add elements that exist during the list tour.

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

data_list = [[apple, 5], [grape, 3], [apple, 2]]

result_data = []
check_list = []

for item in data_list:
    if item[0] not in check_list:
        for result_item in result_data:
            if result_item[0] == item[0]:
                result_item[0] += item[0]

If you find the same fruit on the list and add the number, it will take too long if you have a large number of elements on the list. How do I fix the code to do it quickly without doing it like that?

python list for

2022-09-20 15:50

2 Answers

data_sum = {}

for fruit, number in data_list:
    data_sum[fruit] = data_sum.get(fruit, 0) + count

2022-09-20 15:50

import pandas as pd

data_list = [['apple', 5], ['grape', 3], ['apple', 2]]
df = pd.DataFrame(data_list)

res = df.groupby(by=[0]).sum()

for idx in res.index:
   print('{0}:{1}'.format(idx, res.loc[idx]))

You can easily do what you want with Pandas. I hope it was helpful.

2022-09-20 15:50

If you have any answers or tips

© 2022 pinfo. All rights reserved.