首页 > 解决方案 > python从文件中读取二维列表中的多行到一维

问题描述

我有如下所示的文本文件:

Cat
Beth
12
female
Dog
Bob
10
male
...
..
.

我想这样存储它: myList = [
[“Cat”,“Beth”,“12”,“female”],
[“Dog”,“Bob”,“10”,“male”],...
]
我想出了这个主意。
我的问题:有没有更短的方法来做到这一点?

with open("sample.txt") as myFile:
   myList = []
   temp = []
   bit = 1
   for line in myFile:
       temp.append(line.strip())
       if bit % 4 == 0:
           myList.append(temp)
           temp = []
       bit += 1

标签: pythonliststoring-data

解决方案


推荐阅读