输出必须是这样的:
[{'id': '1', 'first_name': 'Heidie','gender': 'Female'}, {'id': '2', 'first_name': 'Adaline', 'gender': 'Female'}, {...}
有一个符合要求的代码片段。
with open('./test.csv', 'r') as file_read:
reader = csv.DictReader(file_read, skipinitialspace=True)
listDict = [{k: v for k, v in row.items()} for row in reader]
print(listDict)
但是,我不明白上面这段代码的一些要点:
listDict = [{k: v for k, v in row.items()} for row in reader]
id
,first_name
,gender
)及其值组成一个列表?for
来实现此代码我阅读了这些答案,但我仍然不明白:
我的csv文件:
id,first_name,last_name,email,gender
1,Heidie,Philimore,hphilimore0@msu.edu,Female
2,Adaline,Wapplington,awapplington1@icq.com,Female
3,Erin,Copland,ecopland2@google.co.uk,Female
4,Way,Buckthought,wbuckthought3@usa.gov,Male
5,Adan,McComiskey,amccomiskey4@theatlantic.com,Male
6,Kilian,Creane,kcreane5@hud.gov,Male
7,Mandy,McManamon,mmcmanamon6@omniture.com,Female
8,Cherish,Futcher,cfutcher7@accuweather.com,Female
9,Dave,Tosney,dtosney8@businesswire.com,Male
10,Torr,Kiebes,tkiebes9@dyndns.org,Male
答案 0 :(得分:1)
您的列表理解:
listDict = [{k: v for k, v in row.items()} for row in reader]
等于:
item_list = []
#go through every row
for row in reader:
item_dict = {}
#in every row go through each item
for k,v in row.items():
#add each items k,v to dict.
item_dict[k] = v
#append every item_dict to item_list
item_list.append(item_dict)
print(item_list)
编辑(更多解释):
#lets create a list
list_ = [x ** 2 for x in range(0,10)]
print(list_)
这将返回:
[0,1,4,9,16,25,36,49,64,81]
您可以这样写:
list_ = []
for x in range(0,10):
list_.append(x ** 2)
因此在该示例中,您读了“向后”
现在假设下一个:
#lets create a list
list_ = [x ** 2 for x in range(0,10) if x % 2 == 0]
print(list_)
这将返回:
[0,4,16,36,64]
您可以这样写:
list_ = []
for x in range(0,10):
if x % 2 == 0:
list_.append(x ** 2)
所以那不是100%向后的,但是应该是合乎逻辑的。希望这对您有帮助!