Python:使用Map / Lambda而不是For-Loop

时间:2014-02-02 13:22:11

标签: python json csv

我正在努力将CSV文件转换为结构化Json文件。

CSV.File

address,type,floor,door
"1","is","an","example"
"2","is","an","example"
"3","is","an","example"
"4","is","an","example"
"5","is","an","example"
"6","is","an","example"
"7","is","an","example"

首先,我阅读了csv文件,并列出了列的所有列项。

import pandas as pd

with open('data.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
    df = pd.read_csv(csvfile)
    listAddress= df.address
    listType= df.type
    listFloor= df.floor
    listDoor=df.door

为了获得这样的列表:

listAddress=["1","2","3","4","5","6","7"]

现在,我想自动化该过程并制作词典列表

Output= []
tempJson =  {"1": 1,"2": "is"}

for i in range(len(listAddress)):
  tempJson["Address"]= listAddress[i]
  tempJson["Type"]= listType[j]
  Output.(tempJson)

json.dumps(output)

这是问题所在,我想制作一个字典列表,我可以使用map在JS中做到这一点。但我不擅长Python。 我可以使用Map

简化最后一段代码吗?
Output: 
[
    {
        "1": 1,
        "2": "is"
    },
    {
        "1": 2,
        "2":"is"
    },
    {
        "1": 3,
        "2": "is"
    },{
        "1": 4,
        "2": "is"
    },
    {
        "1": 5,
        "2":"is"
    },
    {
        "1": 6,
        "2": "is"
    },
    {
        "1": 7,
        "2": "is"
    }
]

2 个答案:

答案 0 :(得分:1)

您可以在此处使用list comprehension

>>> from pprint import pprint
>>> import csv
>>> with open('data.csv') as f:
    next(f)  #skip the header
    reader = csv.reader(f, delimiter=',', quotechar='"')
    d = [{'1':int(row[0]), '2': row[1]} for row in reader]
...     
>>> pprint(d)
[{'1': 1, '2': 'is'},
 {'1': 2, '2': 'is'},
 {'1': 3, '2': 'is'},
 {'1': 4, '2': 'is'},
 {'1': 5, '2': 'is'},
 {'1': 6, '2': 'is'},
 {'1': 7, '2': 'is'}]

答案 1 :(得分:0)

一个简单的改变就是

Output= []
tempJson =  {"1": 1,"2": "is"}

for i in range(len(listAddress)):
  tempJson["Address"]= listAddress[i]
  tempJson["Type"]= listType[i]
  Output.append(tempJson.copy())
可能被认为更加pythonic的东西是:

output = [{"1": 1, "2": "is", "Address": a, "Type": t}
          for a, t in zip(listAddress, listType)]