[英]How to create a new list with just numbers and words/phrases from a original list with both numbers and words in python?
The current list looks like this: line_list = ['Rent 350', 'Gas 60', 'Food 50', 'Clothing 40', 'Car Payment 500', 'Electric Bill 150', 'Cell Phone Bill 150', 'Miscellaneous 10']
当前列表如下所示:
line_list = ['Rent 350', 'Gas 60', 'Food 50', 'Clothing 40', 'Car Payment 500', 'Electric Bill 150', 'Cell Phone Bill 150', 'Miscellaneous 10']
I would like the output to look like this:我希望 output 看起来像这样:
labels = ['Rent', 'Gas', 'Food', 'Clothing', 'Car Payment', 'Electric Bill', 'Cell Phone Bill', 'Miscellaneous']
amount = ['350', '60', '50', '40','500','150', '150', '10']
Basically, I'm trying to split the list into one list with just numbers and one list with the words/phrases.基本上,我试图将列表拆分为一个仅包含数字的列表和一个包含单词/短语的列表。
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)
Assuming the structure of your phrases is as in the example (some words and a number in the end), you could use re
's split
:假设您的短语结构与示例中的结构相同(最后是一些单词和一个数字),您可以使用
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']
You might get tempted to use list-comprehension here but that would mean going over the list twice, so an old-fashioned loop will be best to loop once and create both lists.您可能会想在这里使用列表理解,但这意味着遍历列表两次,因此最好使用老式循环循环一次并创建两个列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.