Python 如何在范围内写入变量数

Python 如何在范围内写入变量数,python,python-2.7,csv,range,Python,Python 2.7,Csv,Range,这是我的代码,我想使用.csv文件中的数字来控制将生成多少个数字 with open('number.csv','rb') as csvfile: reader = csv.DictReader(csvfile) num = [row['123'] for row in reader] a = [randint(12, 20) for i in range(???)] ???是.csv文件中的值。所以问题是如何写入 .csv类似于(在我的.csv中只有一个值。['5']): 因此CSV文件中只

这是我的代码,我想使用.csv文件中的数字来控制将生成多少个数字

with open('number.csv','rb') as csvfile:
reader = csv.DictReader(csvfile)
num = [row['123'] for row in reader]
a = [randint(12, 20) for i in range(???)]
???是.csv文件中的值。所以问题是如何写入


.csv类似于(在我的.csv中只有一个值。['5']):


因此CSV文件中只有1个值。

首先,不要使用列表理解来读取一行。使用获取所需的唯一行

接下来,必须将单个值转换为整数:

with open('number.csv','rb') as csvfile:
    reader = csv.DictReader(csvfile)
    row = next(reader)
count = int(row['123'])
a = [randint(12, 20) for i in range(count)]

您有一个字符串列表(
num
将是
['5','…','…']
)。您想使用哪一个来确定为
a
调用
randint()
的次数?在my.csv中,只有一个值。[5']你能把你的问题补充一下吗?在这种情况下,不需要使用列表。error ocated.self.\u fieldnames=self.reader.next()value错误:对关闭的文件执行I/O操作。你介意修一下吗?@zhou:你的
csvfile
对象已经关闭了。您需要小心将
next()
调用放入
with
块中,以便文件尚未关闭。
with open('number.csv','rb') as csvfile:
    reader = csv.DictReader(csvfile)
    row = next(reader)
count = int(row['123'])
a = [randint(12, 20) for i in range(count)]