当前列表如下所示:line_list = ['Rent 350', 'Gas 60', 'Food 50', 'Clothing 40', 'Car Payment 500', 'Electric Bill 150', 'Cell Phone Bill 150', 'Miscellaneous 10']
我希望输出看起来像这样:
labels = ['Rent', 'Gas', 'Food', 'Clothing', 'Car Payment', 'Electric Bill', 'Cell Phone Bill', 'Miscellaneous']
amount = ['350', '60', '50', '40','500','150', '150', '10']
基本上,我试图将列表分为一个只有数字的列表和一个包含单词/短语的列表。
line_list = ['Rent 350', 'Gas 60', 'Food 50', 'Clothing 40', 'Car Payment 500', 'Electric Bill 150', 'Cell Phone Bill 150', 'Miscellaneous 10']
expenses = []
costs = []
for *expense, cost in map(str.split, line_list):
expenses.append(" ".join(expense))
costs.append(cost)
假设短语的结构与示例中相同(最后是一些单词和一个数字(,则可以使用re
的split
:
>>> import re
>>> word_list = []
>>> num_list = []
>>> for phrase in line_list:
parts = re.split(" (?=d)", phrase)
word_list.append(parts[0])
num_list.append(parts[1])
>>> word_list
['Rent', 'Gas ', 'Food', 'Clothing', 'Car Payment', 'Electric Bill', 'Cell Phone Bill', 'Miscellaneous']
>>> num_list
['350', '60', '50', '40', '500', '150', '150', '10']
你可能会想在这里使用列表理解,但这意味着要遍历列表两次,所以老式的循环最好循环一次并创建两个列表。