【问题标题】:Make while loop print out multiple lists with csv.reader使用 csv.reader 使 while 循环打印出多个列表
【发布时间】:2014-11-28 11:03:31
【问题描述】:

我有一个 excel 文档,其中包含我希望我的 python 代码打印出来的信息。为了让大家了解我的 excel 文档的外观,我将打印一些代码:

import csv
file = csv.reader(open("n:\population.csv"))
print file.next()

这给了我们以下输出:

   ['country', 'country isocode', 'year', 'POP']

但这不是我要打印的部分,相关信息在其他行,所以如果我再输入一个打印 file.next() 我们得到以下信息:

['Netherlands', 'NLD', '1950', '10113.527']

如果我需要相关信息,现在我只需要打印出年份和人口 (POP),并为文档中的每一行执行此操作。所以我想出了以下代码来做到这一点:

import csv
file = csv.reader(open("population.csv"))
print file.next()


def print_population_list(filename):
    population_list_length = len("population.csv")
    number = 0
    line = file.next()
    while number < population_list_length:
        print line[2:]
        population_list_length = population_list_length - 1



print_population_list('N:\population.csv')

问题是这段代码的输出看起来像:

['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']
['1950', '10113.527']

那么如何让我的代码打印出文档的下一行,而不是一遍又一遍地打印同一行,直到数字 > population_list_length。

如果有人能帮我解决这个问题,我会很感激的

【问题讨论】:

    标签: list python-2.7 csv while-loop repeat


    【解决方案1】:

    马上,您没有做的一件事就是在 while 循环中(或在 for 循环中)推进该行。

    您已将 line 定义为 file.next(),但随后告诉它一遍又一遍地打印同一行中的部分。

    试试这个,注意在打印数据后在每个循环结束时推进行:

    def print_population_list(filename):
        population_list_length = len("population.csv")
        number = 0
        line = file.next()
        while number < population_list_length:
            print line[2:]
            # the next line of code advances the line in the file
            line = file.next()
            population_list_length = population_list_length - 1
    
        # you don't need to advance the line here, 
        # as you've already advanced it at the end of the last loop
    
        for contry, isocode, year, population in 
            print line[2:]
            # the next line of code advances the line in the file
            line = file.next()
            population_list_length = population_list_length - 1
    

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 2014-08-12
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多