简体   繁体   English

蟒蛇。 如何根据文件中的行数动态创建变量?

[英]Python. How to dynamically create variables based on number of lines in a file?

Is it possible to create variables based on the number of lines in a file? 是否可以根据文件中的行数创建变量?

For example, assuming the file will always have an even-number of lines. 例如,假设文件将始终具有偶数行。 If the file has 4 lines I want to create 2 variables. 如果文件有4行,我想创建2个变量。 var1 will contain the first 2 lines and var2 will contain the following 2 lines. var1将包含前两行,而var2将包含后两行。 If the file has 10 lines I want to create 5 variables. 如果文件有10行,我想创建5个变量。 Again the first var will have the first 2 lines, and the next var will have the following 2 lines and so on... 同样,第一个变量将具有前两行,而下一个变量将具有以下两行,依此类推...

It is almost always a bad idea to create variable names based on some programmatic value. 基于某些编程值创建变量名几乎总是一个坏主意。 Instead use a native data structure. 而是使用本机数据结构。 In this case it sounds like a list is what you need. 在这种情况下,听起来像是您需要的list

Here is a way to loop through a file and collect pairs of lines into a list of lists. 这是一种遍历文件并将行对收集到列表列表中的方法。

var = []
last_line = None
for line in open('data.txt', 'rU'):
    if last_line:
        var.append([last_line, line.strip()])
        last_line = None
    else:
        last_line = line.strip()
if last_line:
    var.append([last_line])
print(var)

Results: 结果:

[['line1', 'line2'], ['line3', 'line4'], ['line5', 'line6']]
from itertools import islice
num_lines = sum(1 for line in open('lines.txt'))
with open("lines.txt", "r+") as f:
    len_of_lines = num_lines
    count_ = 0
    while count_ < len_of_lines:
        var = list(islice(f, 2))
        # something with var
        print(var)
        count_ += 2
   >>>['xascdascac\n', 'ascascanscnas\n']
      ['ascaslkckaslca\n', 'ascascacac\n']
      ['ascascaca\n', 'ascacascaca\n']
      ['ascascascac\n']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM