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

String not allowed? How to define max limit of ranges as cell values from csv column?

希望不正确的代码仍然传达了我正在尝试做的事情。我在使用 enumerate (and range) b/c 'count' is interpreted as a string 时收到一个字符串错误,而我希望它被解释为一个整数值。我想创建具有从 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.

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

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

count = int(row[1])

2) 创建一个介于 0 和计数之间的列表:

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 

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

正如您所使用的那样,您不会收到字符串错误 - 您使用的 enumerate 是错误的,因为它需要一个可迭代对象作为第一个参数。但在这种情况下,无论如何都不需要枚举。

不过一般来说,你从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]