【问题标题】:Printing the data from 2 different lists and their index打印来自 2 个不同列表的数据及其索引
【发布时间】:2019-02-08 18:43:19
【问题描述】:

我正在以这种方式读取 CSV 文件:

import csv

with open('X.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    objectids = []
    municodes = []


    for row in readCSV:
        objectid = row[2]
        municode = row[5]
        objectids.append(objectid)
        municodes.append(municode)

然后我想在屏幕上打印诸如 rowlinenumber、“objectids”和“municodes”之类的内容。我试过这样: checkfirstline = 0

for uniqueobjid in objectids:
    if checkfirstline is not 0: #to jump the first line (on this data it's a header)
        print("obdid: " + str(uniqueobjid) + " -- city: " )
    else:
        checkfirstline += 1

我的问题是我不确定如何从同一位置获取 rowlinenumber(索引)和“municodes”。

我期待一个结果 +- 像这样:

row:0 ;  obdid: 3; cityid: 20
row:1 ;  obdid: 4; cityid: 20

【问题讨论】:

    标签: python csv iterator


    【解决方案1】:

    由于csv.reader 是一个迭代器,您可以在其上调用一次next 以“跳过”标头:

    with open('X.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        next(readCSV)
        # as before
    

    然后在迭代列表时使用enumeratezip

    for idx, (a, b) in enumerate(zip(objectids, municodes)):
        print(f'row:{idx}; obdid: {a}; cityid: {b}')
    

    为了可读性和性能,我们使用 f-strings,在 Python 3.6+ 中可用。

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多