仅在csv文件列表中打印值

时间:2017-07-27 00:54:22

标签: list csv tuples python-3.6

我有一个小程序可行,但不是我想要的。

上半部分正常。

写(下)半部分确实有效,但我感兴趣的只是值 在元组中。没别了。

我的代码:

import json
import csv

jsonfile = "f:\mark\python\data.json"

with open(jsonfile, "r") as jfile:
    jfile_decode = json.load(jfile)
    # Create a list of tuples with a list comprehension
    jlist = [[(k, v) for k, v in d.items() if k in ['city', 'state', 'population', 'rank']] for d in jfile_decode]
    # print(jlist)  - Just for testing to make sure the output is what I wanted -


outputfile = "f:\mark\python\data.csv"
with open(outputfile, 'w') as f:
    csv_out = csv.writer(f, delimiter=' ')
    csv_out.writerow(['city', 'state', 'population', 'rank'])
    for row in jlist:
        csv_out.writerow(row)

我目前得到的输出:

city state population rank

"('city', 'New York')" "('population', '8405837')" "('rank', '1')" "('state', 'New York')"

"('city', 'Los Angeles')" "('population', '3884307')" "('rank', '2')" "('state', 'California')"

"('city', 'Chicago')" "('population', '2718782')" "('rank', '3')" "('state', 'Illinois')"

"('city', 'Houston')" "('population', '2195914')" "('rank', '4')" "('state', 'Texas')"

我想要的是:(只是元组值。没有别的)

city state population rank

'New York' 'New York' '8405837' '1'

'Los Angeles' 'California' '3884307' '2'

1 个答案:

答案 0 :(得分:2)

您可以评估字符串,并获取所需的元素:

print(" ".join([col[1].strip('!"') for col in row]))
  

编辑   要删除字符串中的双引号,请使用.strip('!"'):

big_tuple = [{'city': 'New York', 'growth_from_2000_to_2013': '4.8%', 'latitude': 40.7127837, 'longitude': -74.0059413, 'population': '8405837', 'rank': '1', 'state': 'New York'},{'city': 'Los Angeles', 'growth_from_2000_to_2013': '4.8%', 'latitude': 34.0522342, 'longitude': -118.2436849, 'population': '3884307', 'rank': '2', 'state': 'California'}]

jlist = [[(k, v) for k, v in d.items() if k in ['city', 'state', 'population', 'rank']] for d in big_tuple]

for row in jlist:
    print(" ".join([col[1] for col in row]))

一个例子:

New York 8405837 1 New York 
Los Angeles 3884307 2 California

结果

{{1}}