如何将单个索引列表转换为多索引Python列表

时间:2016-05-18 14:11:58

标签: python python-2.7 python-3.x

在application-1中我将 n 元素的列表(list_1_app_1)保存在文件中,稍后应用程序-2读取该文件。

application-1

list_1_app_1 = []
def afunction(self):    
    [...]
    self.buildList_1(self.ulx, self.uly, self.brx, self.bry)

def buildList_1(self, ul_x, ul_y, br_x, br_y):
        nrows = br_y - ul_y
        ncols = br_x - ul_x
        self.list_1 = [0 for xx in range(nrows*ncols)]
        global list_1_app_1
        list_1_app_1 = self.list_1
        for i in range(0, nrows):
            for j in range(0, ncols):
                if(i == 0 or i == (nrows -1) or j == 0 or j == (ncols-1)):
                    list_1_app_1[j + i*ncols] = -1
[...]
afunction()
[..]
list_1_file = open('list_1.txt', 'w+')
list_1_file.write(("%s \n" %(list_1_app_1)))

application-2 中,我读了list_1.txt

def read_list_1_File(list_file):
    with open(list_file, "r") as ins:
        content = [x.strip() for x in ins]
    return content
list_1_app_2 = read_list_1_File("list_1.txt")

在app-1中,我将列表list_1-app_1[]复制到"list_1.txt"文件

#print list_1.txt    
[-1, -1, -1, -1, -1,...]

所以,当我在app-2中阅读"list_1.txt"时,我会得到包含list_1_app_1[]中所有list_1_app_2[0]个元素的一维列表。

>>>print list_1_app_2    
['[-1, -1, -1, -1, -1,...]']

这不是我需要的。 我需要list_1_app_2作为(nrows * ncols)维度列表,可能避免使用昂贵的(nrows * ncols)循环。 任何见解都将非常感激,

谢谢

2 个答案:

答案 0 :(得分:1)

尝试此更改:

for item in list_1_app_1:
  list_1_file.write("%s\n" % item)

答案 1 :(得分:1)

如果您只使用共享文件是在应用程序之间保存数据,则可以使用python自己的pickle模块中的序列化函数。

申请1

with open('list_1.txt', 'wb') as list_1_file:
    pickle.dump(list_1_app_1, list_1_file)

申请2

with open('list_1.txt') as list_1_file:
    list_1_app_2 = pickle.load(list_1_file)