Pythonic way to change all items in a list and save the list in a .txt file

I have a list of strings.

theList = ['a', 'b', 'c'] 

I want to add integers to strings, the result is this output:

 newList = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'] 

I want to save this in a .txt file in this format:

 a0 b0 c0 a1 b1 c1 a2 b2 c2 a3 b3 c3 

Attempt:

 theList = ['a', 'b', 'c'] newList = [] for num in range(4): stringNum = str(num) for letter in theList: newList.append(entry+stringNum) with open('myFile.txt', 'w') as f: print>>f, newList 

Now I can save the file myFile.txt, but the text in the file reads:

 ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'] 

Any advice on more pythonic ways to achieve my goal is greatly appreciated.

+6
source share
4 answers

Instead of your last line use:

 f.write("\n".join(newList)) 

This will write the lines in newList, separated by newlines, in f. Note: if you really don't need newList, you can combine your two loops and write lines as you go:

 the_list = ['a', 'b', 'c'] with open('myFile.txt', 'w') as f: for num in range(4): for letter in the_list: f.write("%s%s\n" % (letter, num)) 
+7
source

It will probably do your job

 with open('myFile.txt', 'w') as f: for row in itertools.product(range(len(theList)+1),theList): f.write("{1}{0}\n".format(*row)) 
+2
source

If you want to compress your code a bit, you can do:

 >>> n = 4 >>> the_list = ['a', 'b', 'c'] >>> new_list = [x+str(y) for x in the_list for y in range(n)] >>> with open('myFile.txt', 'w') as f: ... f.write("\n".join(new_list)) 
+2
source

What you do is fine - one of the points in Zen of Python is "just better than complicated." You can easily rewrite this as a one-line (perhaps using a nested list comprehension), but what you have is nice and easy to understand.

But there are a few minor changes I can make:

  • It is often better to use more portable serialization in a text file, such as JSON, through Python json.dump(newList, f) . It's good to use the with statement.
  • You don't need a separate stringNum variable - str(num) inside the add is just as good
  • Follow the PEP-8 naming conventions, so new_list instead of newList
  • Nitpicking: your question title says β€œchange all items in a list” when your code actually creates a new list. This is usually a Python thing anyway - side effects, such as changing the list in place, are often less useful.
+1
source

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


All Articles