简体   繁体   中英

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']

I would like the output to look like this:

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 :

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM