[英]Regex in Python: Separate words from numbers JUST when not in list
[英]How to create a new list with just numbers and words/phrases from a original list with both numbers and words in python?
當前列表如下所示: line_list = ['Rent 350', 'Gas 60', 'Food 50', 'Clothing 40', 'Car Payment 500', 'Electric Bill 150', 'Cell Phone Bill 150', 'Miscellaneous 10']
我希望 output 看起來像這樣:
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']
您可能會想在這里使用列表理解,但這意味着遍歷列表兩次,因此最好使用老式循環循環一次並創建兩個列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.