前提
Pythonでコードを書いています。
アルゴリズムに関して実現したいことがあるのですが、わかりそうでわからない為時間がかかっています。
是非お力添えいただきたいです。
実現したいこと
以下のリストを加工してまとめたいです。
python
1[ 2 {'ID': 1, 'fruits': 'りんご', 'total ': 1, 'product': ['青森'], 'counts': [1], 'remarks': ['酸味']}, 3 {'ID': 2, 'fruits': 'もも', 'total': 2, 'product': ['山梨'], 'counts': [2], 'remarks': ['甘味']}, 4 {'ID': 3, 'fruits': 'ぶどう', 'total': 1, 'product': ['山梨'], 'counts': [1], 'remarks': ['酸味']}, 5 {'ID': 2, 'fruits': 'もも', 'total': 1, 'product': ['福島'], 'counts': [1], 'remarks': ['甘味']}, 6 {'ID': 5, 'fruits': 'みかん', 'total': 1, 'product': ['愛媛'], 'counts': [1], 'remarks': ['うま味']}, 7 {'ID': 5, 'fruits': 'みかん', 'total': 3, 'product': ['和歌山'], 'counts': [3], 'remarks': ['酸味']}, 8 {'ID': 1, 'fruits': 'りんご', 'total': 2, 'product': ['福島'], 'counts': [2], 'remarks': ['酸味']}, 9 {'ID': 5, 'fruits': 'みかん', 'total': 2, 'product': ['静岡'], 'counts': [2], 'remarks': ['苦味']}, 10 ]
- リスト内にdict型の値が入っています。
- keyである"ID"が決まれば"fruits"も決まります。
- 辞書型のkeyである'product''counts''remarks'の値はリスト型です。
纏めた結果は以下となります。
python
1[ 2 {'ID': 1, 'fruits': 'りんご', 'total': 3, 'product': ['青森', '福島'], 'counts': [1,2], 'remarks': ['酸味','酸味']}, 3 {'ID': 2, 'fruits': 'もも', 'total': 3, 'product': ['山梨', '福島'], 'counts': [2,1], 'remarks': ['甘味','甘味']}, 4 {'ID': 3, 'fruits': 'ぶどう', 'total': 1, 'product': ['山梨'], 'counts': [1], 'remarks': ['酸味']}, 5 {'ID': 5, 'fruits': 'みかん', 'total': 6, 'product': ['愛媛','和歌山','静岡'], 'counts': [1,3,2], 'remarks': ['うま味','酸味','苦味']}, 6 ]
- 'ID'及び'fruits'が重複しないように辞書型をまとめ、'product''counts''remarks'の値をリストに追加していく。
- countsの値であるリストの合計が'total'の合計となる。
該当のソースコード
python
1list = [ 2 {'ID': 1, 'fruits': 'りんご', 'total ': 1, 'product': ['青森'], 'counts': [1], 'remarks': ['酸味']}, 3 {'ID': 2, 'fruits': 'もも', 'total': 2, 'product': ['山梨'], 'counts': [2], 'remarks': ['甘味']}, 4 {'ID': 3, 'fruits': 'ぶどう', 'total': 1, 'product': ['山梨'], 'counts': [1], 'remarks': ['酸味']}, 5 {'ID': 2, 'fruits': 'もも', 'total': 1, 'product': ['福島'], 'counts': [1], 'remarks': ['甘味']}, 6 {'ID': 5, 'fruits': 'みかん', 'total': 1, 'product': ['愛媛'], 'counts': [1], 'remarks': ['うま味']}, 7 {'ID': 5, 'fruits': 'みかん', 'total': 3, 'product': ['和歌山'], 'counts': [3], 'remarks': ['酸味']}, 8 {'ID': 1, 'fruits': 'りんご', 'total': 2, 'product': ['福島'], 'counts': [2], 'remarks': ['酸味']}, 9 {'ID': 5, 'fruits': 'みかん', 'total': 2, 'product': ['静岡'], 'counts': [2], 'remarks': ['苦味']}, 10 ] 11new_list = [] 12for data in list: 13 for new_data in new_list: 14 if not data["ID"] in new_data["ID"]: 15 new_list.append({'ID':data["ID"],'fruits':data["fruits"]})
試したこと
⑴新たなリストnew_listを用意してlistをループで回す。
⑵new_listの中にlistのデータ”ID”と"fruits"がなければappendしていく。
⑶リストが回し終わったら、再度new_listを回し、counts内の数字を足してtotalの値を書き換える。
という流れになるとおもうのですが、⑴と⑵がうまく実装できません。
補足情報(FW/ツールのバージョンなど)
Python3.7.9を使用
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/07/06 02:49