简体   繁体   English

通过文本输入创建列表列表

[英]Creating a list of list from a text input

I am attempting to create a list that contains lists that is read in from a .txt file. 我正在尝试创建一个包含从.txt文件中读取的列表的列表。 Preferably the inner list well be integers 内部列表最好是整数

I have created two variables created from the text file sink which is the first and raw which is a slice of the orginal text file from [1:] 我已经创建了两个从文本文件接收器创建的变量,第一个是接收器,而raw是从[1:]开始的原始文本文件的一部分

example input from txt file 来自txt文件的示例输入

4,0,5,3,0,0,0,2,4,0,0,0,5,0,0,0,0 4,0,5,3,0,0,0,2,4,0,0,0,5,0,0,0,0

sink = 4 水槽= 4

raw = ['0', '5', '3', '0', '0', '0', '2', '4', '0', '0', '0', '5', '0', '0', '0', '0'] 原始= ['0','5','3','0','0','0','2','4','0','0','0','5' ,“ 0”,“ 0”,“ 0”,“ 0”]

The first number represents the division (4) and well change as the lists get larger or smaller. 第一个数字表示除法(4),并且随着列表的增大或减小而发生良好的变化。 So I would want to create something like this g = [[0,5,3,0],[0,0,2,4],[0,0,0,5],[0,0,0,0]] 所以我想创建类似g = [[0,5,3,0],[0,0,2,4],[0,0,0,5],[0,0,0,0 ]]

Apologies I deleted my attempts. 抱歉,我删除了尝试。

class Reader:
    #place holder for rawData
   rawData = []
   file = open("test4.txt")
   rawData = file.read()
   file.close()     
   rawData = rawData.split(',')

r = Reader()
sink = int(r.rawData[0])
source = 0 #(this is for calculations in other parts of the program)
raw = r.rawData[1:]

Assuming that the length of raw will always be divisible by sink this will get you what you need! 假设未加工的长度总是可以被水槽整除的,这将为您提供所需的东西!

sink = 4
raw = ['0', '5', '3', '0', '0', '0', '2', '4', '0', '0', '0', '5', '0', '0', '0', '0']

g = [raw[i:i+sink] for i in range(0, len(raw), sink)]

print(g)

If you prefer it not in a comprehension then this would be the loop: 如果您不喜欢它,那么这就是循环:

sink = 4
raw = ['0', '5', '3', '0', '0', '0', '2', '4', '0', '0', '0', '5', '0', '0', '0', '0']

g = []
for i in range(0, len(raw), sink):
    g.append(raw[i:i+sink])

print(g)

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

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