使用for循环创建一系列元组 [英] create a series of tuples using a for loop
问题描述
tup(i)= inLine
其中 inLine
是来自文件的行, tup(i)
是元组它存储在。 i
随着循环的进行而增加。然后我可以打印任何类似于
print tup(100)
按照循环描述创建元组不是一个好的选择,因为它们是不可变的。
这意味着每当你为你的元组添加一个新的行,你真的创建一个新的元组与新的元组相同的值,再加上你的新行。这是低效的,一般应该避免。
如果你所需要的是通过索引引用行,你可以使用一个列表:
lines = []
inFile中的行:
lines.append(line)
print行[3]
如果您真的需要一个元组,
lines = tuple(lines)
I have searched and cannot find the answer to this even though I am sure it is already out there. I am very new to python but I have done this kind of stuff before in other languages, I am reading in line form a data file and I want to store each line of data in it's own tuple to be accessed outside the for loop.
tup(i) = inLine
where inLine
is the line from the file and tup(i)
is the tuple it's stored in. i
increases as the loop goes round. I can then print any line using something similar to
print tup(100)
Creating a tuple as you describe in a loop isn't a great choice, as they are immutable.
This means that every time you added a new line to your tuple, you're really creating a new tuple with the same values as the old one, plus your new line. This is inefficient, and in general should be avoided.
If all you need is refer to the lines by index, you could use a list:
lines = []
for line in inFile:
lines.append(line)
print lines[3]
If you REALLY need a tuple, you can cast it after you're done:
lines = tuple(lines)
这篇关于使用for循环创建一系列元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!