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

时间:2015-04-21 01:08:04

标签: python list

我不确定之前是否已经提出此问题,但这是我想要做的事情:

我有一个清单:

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

我想使用flavor将它们分成每个单独的列表,在这种情况下是'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的初学者,这很难吗?谢谢!

2 个答案:

答案 0 :(得分:0)

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)

现在,foodlists['orange']foodlists['lemon']是您之后的列表

答案 1 :(得分:0)

这个怎么样:

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('_')将句子分成单词列表,然后检查食物是否在该列表中。


理论上,你可以做if 'orange' in food,但如果在另一个单词中找到子字符串,则会失败。例如:

>>> s='I_appeared_there'

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

yes

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

>>>