data_list = [[apple, 5], [grape, 3], [apple, 2]]
result_data = []
check_list = []
for item in data_list:
if item[0] not in check_list:
result_data.append(item)
check_list.append(item[0])
else:
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
data_sum = {}
for fruit, number in data_list:
data_sum[fruit] = data_sum.get(fruit, 0) + count
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.
© 2024 OneMinuteCode. All rights reserved.