字符串不允许?如何将范围的最大限制定义为来自csv列的单元格值?

时间:2015-04-17 04:08:24

标签: python arrays csv enumeration

希望错误的代码仍能传达我想要做的事情。我使用枚举(和范围)b / c'计数'当我反而希望它被解释为整数值时被解释为一个字符串。我想创建整数值从0到计数值的数组。如果它有帮助,我的目的是只在给出每个值的频率时创建一个值列表。谢谢!

import csv, sys

outputCSV = open(r"C:\Users\Out.csv")
inputCSV = open(r"C:\Users\Slope.csv")

reader = csv.reader(inputCSV, delimiter = ',')
writer = csv.writer(outputCSV, delimiter = ',')

for row in reader:
    count = row[1]
    countArray = enumerate(0, count) #make list of consecutive integers from 0 to value of count

    while i <= max(countArray):
        print row[0]                #print row value as many times as there are integers in the range 0 through the max of countArray. The printed row value should have same index as the current count index.

2 个答案:

答案 0 :(得分:0)

这里有几个问题。我不确定你要做什么。

1)要消除错误,只需将您的计数转换为整数:

count = int(row[1])

2)创建范围介于0和count之间的列表:

countArray = range(count+1)

3)你有一个无限循环:

# i is not initialized => another error
while i <= max(countArray): # max(countArray) = count => why create the array in the first place?
    print row[0]            # i is not altered so i <= max(countArray) is always True => infinite loop:

也许你想要的是:

for i in countArray:
    print row[0] # That loop works but i don't know if it does what you need 

答案 1 :(得分:0)

根据我的理解,CSV文件中的每一行都有一个数字和一个计数;并且您希望为每一行创建一个重复计数次数的列表。

正如您使用它,您将不会收到字符串错误 - 您使用枚举错误,因为它期望迭代作为第一个参数。但在这种情况下,无论如何都不需要枚举。

一般来说,从csv读取的内容是字符串,因此需要将其转换为整数。你可以这样做:

for row in reader:
    count = int(row[1])
    num = int(row[0])
    for i in range(count):
        print(num)

或者您可以使用理解并立即获取所有列表:

nums = [[int(row[0])] * int(row[1]) for row in reader]