我不确定之前是否已经提出此问题,但这是我想要做的事情:
我有一个清单:
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的初学者,这很难吗?谢谢!
答案 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"
>>>