Py学习  »  Python

如何在python中创建一个只包含数字和单词/短语的新列表?

QMan5 • 5 年前 • 1572 次点击  

当前列表如下: 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']

基本上,我试图将列表分成一个只有数字的列表和一个包含单词/短语的列表。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50014
 
1572 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Tomerikoo
Reply   •   1 楼
Tomerikoo    5 年前

假设短语的结构与示例中的一样(一些单词和结尾的数字),可以使用 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']

在这里,您可能会尝试使用列表理解,但这意味着要对列表进行两次遍历,因此老式的循环最好只循环一次并创建两个列表。

user10987432
Reply   •   2 楼
user10987432    5 年前
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)