繁体   English   中英

如何从 python 中的数字和单词的原始列表中创建仅包含数字和单词/短语的新列表?

[英]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)

假设您的短语结构与示例中的结构相同(最后是一些单词和一个数字),您可以使用resplit

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

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