您如何根据条件使用.split()函数?
假设我有原始数据:
Apples,Oranges,Strawberries Green beans,Yellow green Beans,Tomatoes,Broccoli
我的预期结果是:
['Apples','Oranges','Strawberries','Green beans','Yellow green Beans','Tomatoes','Brocolli']
请注意,'Strawberries'
和'Green beans'
已被拆分。
将此方法分解为预期方式的最佳方法是什么?
答案 0 :(得分:0)
也许是这样的?我正在利用你的食物是多元的这个事实:
#!/usr/local/cpython-3.3/bin/python
def splitter(string, use_s_trick=False):
plant_foods_list = string.split(',')
for plant_food in plant_foods_list:
if use_s_trick:
words = plant_food.split(' ')
words_list = []
for word in words:
words_list.append(word)
if word.endswith('s'):
yield ' '.join(words_list)
words_list = []
else:
yield plant_food
plant_foods_str = 'Apples,Oranges,Strawberries Green beans,Yellow green Beans,Tomatoes,Broccoli'
for plant_food in splitter(plant_foods_str, use_s_trick=True):
print(plant_food)