Create and initialize python list

I am stuck in creating a list using python.

I want to make mxn files, such as file00.txt, file01.txt, ... and file99.txt, but when I tried to do this, it shows some errors. Please let me help.

filename = [] for i in range(0, sm): filename.append('') for j in range(0, sn): filename[i].append('') 

Thanks.

+4
source share
4 answers

You can try something like this:

 filenames = [] for i in range(0, sm): row = [] for j in range(0, sn): row.append('') # I assume you want to do something more here filenames.append(row) 
+4
source

after i set to 0, you add empyty line as the file name [0]. in the second loop in a row

  filename[i].append('') 

it means that you are really calling

  ''.append('') 

So your error should be:

  AttributeError: 'str' object has no attribute 'append' 

Hint: post the error text when asking questions, try to find out what the error text says about the error.

0
source
 filenames = [] for i in range(100): filenames.append((str(i) if len(str(i)) > 1 else str(0) + str(i)) + ".txt") 

At the end, you will get the files file00.txt, file01.txt, ... and file99.txt in your filenames list.

 filenames_mxn = [] for i in range(m): filenames_i = [] for j in range(n): filenames_i.append(filenames[i*n + j]) filenames_mxn.append(filenames_i) 

Your files are now stored in the mxn matrix.

0
source

multidimensional lists of elements of the same type are a bit pointless. try a simple simple list, it is easy to make and easy to use:

 >>> filenames = ['file' + i + j + '.txt' for i in '0123456789' for j in '0123456789'] >>> filenames ['file00.txt', 'file01.txt', 'file02.txt', ..skipped.. 'file97.txt', 'file98.txt', 'file99.txt'] 
0
source

Source: https://habr.com/ru/post/1413071/


All Articles