0

The python code is:

resolution = (4,4,4)
permList = []
with open("perm.txt",'r') as perm:
    file_lines = list(perm)
    for i in range(0, len(file_lines), resolution[2]):
        permList.append([list(line.rstrip()) for line in file_lines[i:i+resolution[2]]])

print(permList)

I'm trying to create a 3d list in python, the values comes from a '.txt' file.

The "perm.txt" file:

1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1
1   1   1   1

This code results in the log:

[[['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1']], [['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1']], [['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1']], [['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1'], ['1', '\t', '1', '\t', '1', '\t', '1']]]

I would like to know how to remove the tabulation '\t', no changing the 3d structure, the objective is:

[[['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1']], [['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1']], [['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1']], [['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1'], ['1', '1', '1', '1']]]

Thanks!

2 Answers2

0

You can loop over each list inside the main list then use an if statement to check if the element of the list is a \t then pop() it if it's true.

for i in range(len(L)):
  for j in range(len(L[0]):
    for k in range(len(L[0][0]):
      if L[i][j][k] == "\t":
        L[i][j].pop(k)

Where L is your 3D list

Charles
  • 555
  • 4
  • 16
0

Use:

list(filter(lambda c: c != '\t', line.rstrip())

in your 6th line

Or Y
  • 2,088
  • 3
  • 16