Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List of sublists, write sublists without brackets

I have a List that is x values long. The list is broken up into different length sublists.I then take these sublists and write them to an output file. Is there a way to print the sublists without the brackets.

Edited to clarfiy:

The actual list is 300 sublists long with 12250 elements in it, and changes with each senario I run. Obviously, this is simplified. Let me change a few things and see if that changes the answers.

i.e.

List=[[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, 12, 15]]

where the output is:

[1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11, 12, 15]

but I want

1, 2, 3
4, 5, 6, 7
8, 9, 10, 11, 12, 15

I want this output in a new variable, say ListMod, so then I can use ListMod in a seperate function to write a file. The file also calls 2 other lists, Time and Size, where Size designates the length of the line in ListMod.

How much does that modify your answers?

like image 890
user2962634 Avatar asked Dec 19 '22 21:12

user2962634


1 Answers

First, the answer:

file.write(','.join(map(repr, List))

Your actual code can't possibly be writing what you claim it is, for multiple reasons:

  • A file's write method will give you a TypeError if you give it a list, not print it out. You have to call str or repr on the list to get something you can write.
  • Calling str or repr on a list puts spaces after the commas, as well as brackets.
  • You've got at least one SyntaxError in your code that would prevent you even getting that far.

So, I have to guess what you're actually doing before I can explain how to fix it. Maybe something like this:

file.write(str(List))

If so, the __str__ method of a list is effectively:

'[' + ', '.join(map(repr, self)) + ']'

You want this without the brackets and without the spaces, so it's:

','.join(map(repr, self))
like image 153
abarnert Avatar answered Dec 27 '22 01:12

abarnert