我的问题与此问题非常相似 Python: split line by comma, then by space
但是我需要向前迈出一步。我的清单实际上看起来像这样
name,phone,monthlysalary,age
Peter,1234567,100000,28
John,22345,200000,30
Mary,32345,300000,40
如果我使用以下方法破坏列表:-
Source="""name,phone,monthlysalary,age
Peter,1234567,100000,28
John,22345,200000,30
Mary,32345,300000,40"""
x = [elem.split(",") for elem in Source.split("\n")]
然后我可以得到如下结果:-
[['name', 'phone', 'monthlysalary', 'age'],
['Peter', '1234567', '100000', '28'],
['John', '22345', '200000', '30'],
['Mary', '32345', '300000', '40']]
但是我需要的是:-
{'Peter': ['1234567', '100000', '28'],
'John': ['22345', '200000', '30'],
'Mary': ['32345', '300000', '40']}
我想使用列表而不是列表:
我可以轻松地编写一个简单的代码,如下所示:-
Source="""name,phone,monthlysalary,age
Peter,1234567,100000,28
John,22345,200000,30
Mary,32345,300000,40"""
x = dict()
_, *lines = Source.split("\n")
for line in lines:
head, *tail = line.split(',')
x[head] = tail
但是我想知道是否可以使用一个衬板来实现这一目标?
答案 0 :(得分:3)
这就是CSV模块的作用:
import csv
data = csv.DictReader(filename, delimiter=",")
答案 1 :(得分:0)
如果您不想使用csv
模块,则可以像这样复制DictReader
的行为:
>>> data = """name,phone,monthlysalary,age
... Peter,1234567,100000,28
... John,22345,200000,30
... Mary,32345,300000,40"""
...
>>> lines = iter(data.splitlines())
>>> head = next(lines).split(",")
>>> [dict(zip(head, line.split(","))) for line in lines]
[{'age': '28', 'monthlysalary': '100000', 'name': 'Peter', 'phone': '1234567'},
{'age': '30', 'monthlysalary': '200000', 'name': 'John', 'phone': '22345'},
{'age': '40', 'monthlysalary': '300000', 'name': 'Mary', 'phone': '32345'}]
如果您希望从更新中获取一种格式的结果格式,请尝试以下操作:
>>> {x[0]: x[1:] for x in (line.split(",") for line in data.splitlines()[1:])}
{'John': ['22345', '200000', '30'],
'Mary': ['32345', '300000', '40'],
'Peter': ['1234567', '100000', '28']}
但是,导入csv
模块的内存消耗和单行代码的好处都可能被高估了。