使用for循环创建一系列元组 [英] create a series of tuples using a for loop

查看:185
本文介绍了使用for循环创建一系列元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我确定它已经在那里了,但我已经搜索了,也找不到答案。我对python很陌生,但是在其他语言之前,我已经完成了这种类型的东西,我正在以行的形式读取一个数据文件,并且希望将每行数据存储在它自己的元组中,以便在for循环之外访问。 / p>

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆