如何在python中将单个列表拆分为多个列表

如何在python中将单个列表拆分为多个列表,python,list,Python,List,我不确定以前是否有人问过这个问题,但我想做的是: 我有一份清单: foods = ['I_want_ten_orange_cookies', 'I_want_four_orange_juices', 'I_want_ten_lemon_cookies', 'I_want_four_lemon_juices'] 我想用味道把它们分开,在这个例子中是'orange'和'lemon': orange = ['I_want_ten_orange_cookies', 'I_want_four_orang

我不确定以前是否有人问过这个问题,但我想做的是:

我有一份清单:

foods = ['I_want_ten_orange_cookies', 'I_want_four_orange_juices', 'I_want_ten_lemon_cookies', 'I_want_four_lemon_juices']
我想用味道把它们分开,在这个例子中是
'orange'
'lemon'

orange = ['I_want_ten_orange_cookies', 'I_want_four_orange_juices']
lemon = ['I_want_ten_lemon_cookies', 'I_want_ten_lemon_juices']
我是Python的初学者,这很难做到吗?谢谢大家!

foods = ['I_want_ten_orange_cookies', 'I_want_four_orange_juices', 'I_want_ten_lemon_cookies', 'I_want_four_lemon_juices']

foodlists = {'orange':[], 'lemon':[]}

for food in foods:
    for name, L in foodlists.items():
        if name in food:
            L.append(food)
现在,
FoodList['orange']
FoodList['lemon']
是您要查找的列表

这个怎么样:

foods = ['I_want_ten_orange_cookies', 'I_want_four_orange_juices', 'I_want_ten_lemon_cookies', 'I_want_four_lemon_juices']

orange=[]
lemon=[]

for food in foods:
    if 'orange' in food.split('_'):
        orange.append(food)
    elif 'lemon' in food.split('_'):
        lemon.append(food) 
这将产生:

>>> orange
['I_want_ten_orange_cookies', 'I_want_four_orange_juices']

>>> lemon
['I_want_ten_lemon_cookies', 'I_want_four_lemon_juices']
如果列表中的项目始终用下划线分隔,则此操作有效

if'orange'in food.split(“')
将句子拆分成一个单词列表,然后检查食物是否在该列表中


从理论上讲,如果食物中有“橙色”,你可以只做
,但如果在另一个单词中找到子字符串,那就失败了。例如:

>>> s='I_appeared_there'

>>> if 'pear' in s:
    print "yes"

yes

>>> if 'pear' in s.split('_'):
    print "yes"

>>>

不,不是。您可以使用列表理解或for循环。我建议你理解清单。给它一个镜头,问我们,如果你是stuck检查这个资源:哇!!!这正是我需要的!!非常感谢您的及时回复!我现在将尝试将其集成到我的代码中。非常感谢你!!!