gpt4 book ai didi

python - 合并 Python 3 中包含相同 LAST 字符串的子列表

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:19 25 4
gpt4 key购买 nike

假设我已经创建了一个带有字符串的列表列表(称为 AllRecipes):

   >>> AllRecipes [['Tomato', 'hot', 'Pasta'], ['Mushrooms', 'Lettuce', 'cold', 'Salad'], ['Chocolate', 'Nuts', 'hot', 'Cookies'], ['Vegetables', 'Lemon', 'cold', 'Pasta'], ['Chocolate', 'Pistachio', 'hot', 'Cookies'], ['Cheese', 'hot', 'Pasta'], ['Lettuce', 'Fruits', 'cold', 'Salad']]

我想组合包含相同 LAST 字符串的子列表,如下所示:1) 取 for i in range(len(AllRecipes)):

AllRecipes[i][-1] == 'Pasta':
AllRecipes[0] = ['Tomato', 'hot', 'Pasta']
AllRecipes[3] = ['Vegetables', 'Lemon', 'cold', 'Pasta']
AllRecipes[5] = ['Cheese', 'hot', 'Pasta']

2)将其变成:

Pasta = { hot: ['Tomato'], hot: ['Cheese'], cold: ['Vegetables', 'Lemon']}

如果我的问题不清楚,请告诉我。预先感谢您的帮助:)

后续问题(现在我已经为每个问题制作了词典):

假设我有一个列表 ToCook = [] 其中 ToCook = ['Pasta', 'Cookies', 'Salad']如何为 ToCook 中的每个项目检索其等效字典?

最佳答案

这可能是最容易用 defaultdict 解决的:

from collections import defaultdict

AllRecipes=[['Tomato', 'hot', 'Pasta'], ['Mushrooms', 'Lettuce', 'cold', 'Salad'], ['Chocolate', 'Nuts', 'hot', 'Cookies'], ['Vegetables', 'Lemon', 'cold', 'Pasta'], ['Chocolate', 'Pistachio', 'hot', 'Cookies'], ['Cheese', 'hot', 'Pasta'], ['Lettuce', 'Fruits', 'cold', 'Salad']]

mydict = defaultdict(list)

for recipe in AllRecipes:
mydict[recipe[-1]].append(recipe[:-1])

for key, vals in mydict.items():
print('{} : {}'.format(key,vals))

这会导致

Pasta : [['Tomato', 'hot'], ['Vegetables', 'Lemon', 'cold'], ['Cheese', 'hot']]
Cookies : [['Chocolate', 'Nuts', 'hot'], ['Chocolate', 'Pistachio', 'hot']]
Salad : [['Mushrooms', 'Lettuce', 'cold'], ['Lettuce', 'Fruits', 'cold']]

关于python - 合并 Python 3 中包含相同 LAST 字符串的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44629229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com