我正在尝试导入信息以创建2D列表,并且我很难用信息填写列表。我一直试图导入信息以创建列表
ROW = 3
COLS = 4
myInfo = ('myInfoFile.txt', 'r')
name = myInfo.readline().rsrip('\n')
while name != '':
address = myInfo.readline()
telNum = float(myInfo.readline())
email = myInfo.readline()
myInfo.close()
list1 = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
for r in range(ROWS):
for c in range(COLS):
#this is the main area
list1[r][c] = myInfo
print(list1)
答案 0 :(得分:0)
两件事是错的
info=[[]*COLS for i in range(ROWS)]
for i in range(ROWS):
for j in range(COLS):
info[i][j]=filename.readline
#if float needed
info[i[[j]=float(info[i][j])
答案 1 :(得分:0)
假设您有一个包含2D矩阵的文本文件,则可以使用:
data_file = open('data.txt')
data = data_file.readlines()
for i in range(len(data)) :
data[i] = list(map(float, data[i].split()))
print(data)
如果你正在使用python2,请将map参数放在map前面。
以下是data.txt的内容:
1 2 3 4 5 6 7 8 9
输出:
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
答案 2 :(得分:0)
因为Python中的数组是动态调整大小的,所以你可以使用<list>.append()
函数向数组添加内容。将数组添加到list1
允许矩阵内有非指定数量的行。这是一些修改过的代码:
# The ROW and COLUMN variables aren't necessary.
myInfo = open('filetxt.txt', 'r')
list1 = [] # Not required to define the size of the array using zeros
while(True):
name = myInfo.readline().rstrip('\n')
if(name != ''): # Check for missing names
address = myInfo.readline().rstrip('\n')
telNum = float(myInfo.readline())
email = myInfo.readline().rstrip('\n')
else:
break
list1.append([name, address, telNum, email])
print(list1)
使用以下测试数据,输出为:[['Alice', '1 River Drive', 3.14159265, 'alice@example.net'], ['Bob', '2 Mountain Way', 127.001, 'bob@example.net'], ['Carl', '33 Oak Tree Avenue', 987.654321, 'carl@example.net']]
使用以下输入:
Alice
1 River Drive
3.14159265
alice@example.net
Bob
2 Mountain Way
127.001
bob@example.net
Carl
33 Oak Tree Avenue
987.654321
carl@example.net