【问题标题】:Python - How to repeat a row of data from a csv filePython - 如何从 csv 文件中重复一行数据
【发布时间】:2015-10-23 15:08:13
【问题描述】:

我认为这会很简单,但我被卡住了。我正在尝试根据人口字段重复一行数据。例如,如果人口为 921,则该行需要重复 921 次,然后根据人口移动到下一行并重复。 csv 文件确实有一个标题。我尝试删除它并遇到问题,所以我把标题放回去了。

i = 0
while i < pop:
    if pop == 'F21_64':
        break
    else:
        # writerow
        i += 1

我不断收到此错误代码。 IndexError: 列表索引超出范围

【问题讨论】:

  • 这段代码不可能产生IndexError。另外,如果pop == 'F21_64' 是真的,你将如何比较i &lt; pop?请阅读此帮助页面:minimal reproducible example
  • 请注意,如果您的 csv 文件包含格式良好的标头,csv.DictReader 将适当地处理它。如果您知道 pop 是一个数字,您可以通过 for _ in range(pop): do stuff 循环重复多次。

标签: python python-2.7


【解决方案1】:

您留下了很多假设,但我会尽力回答。一方面,不清楚你想用 pop 做什么,除了你想做的事情是它的值的次数(打印到屏幕,输出到文件???)我会假设打印到屏幕。

我想你正在尝试做这样的事情:(假设你的人口字段在第 2 列)

for row in rows[1:]:            #dont look at the header row
    pop = row.split(',')[1]     #isolate just the pop value
    popvalue = int(pop)         #convert to int
    for i in range(0,popvalue): #for the number of the value...
        print row               #do the thing you want with the entire row

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2017-12-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多