11

I have a list, in which is another list and I want to doc.write(a)

a = [[1, 2, "hello"],
     [3, 5, "hi There"],
     [5,7,"I don't know"]]
doc.write(''.join(a))



TypeError: sequence item 0: expected str instance, list found

How can I handle this, do I have to make a for-loop in which I join and add all the sublists?

The real goal was to make it somehow readable for human beeing, but I didn't wanted a finished solution from you.

7
  • What do you want to do with the numbers? Oct 31, 2013 at 22:39
  • 3
    Please show the actual output you want.
    – abarnert
    Oct 31, 2013 at 22:39
  • I want to write the list in a textfile. Somehow. Oct 31, 2013 at 22:51
  • @inetphantom: And you don't care how at all? It doesn't need to be re-parseable by your code, or readable by a human being, or importable into some other program, or anything? In that case, just do write('stuff') and you're done.
    – abarnert
    Oct 31, 2013 at 23:09
  • @abarnert What is 'stuff' ??
    – eyquem
    Oct 31, 2013 at 23:26

7 Answers 7

13

You can try something like

>>> a = [[1, 2, "hello"],[3, 5, "hi There"],[5,7,"I don't know"]]
>>> 
>>> ''.join(str(r) for v in a for r in v)
"12hello35hi There57I don't know"

i.e.

doc.write(''.join(str(r) for v in a for r in v))
1
  • This has been a long time since that answer - with '\t'.join() this can be beautified to a tab separated list which might be more readable. Jan 15, 2019 at 13:06
4

There are different legal things you can do, and no way for anyone to say which one is right without knowing which one you want.


First, you can just write the str or repr of a:

>>> a=[[1, 2, "hello"],[3, 5, "hi There"],[5,7,"I don't know"]]
>>> repr(a)
'[[1, 2, \'hello\'], [3, 5, \'hi There\'], [5, 7, "I don\'t know"]]'

Note that this is what print does (it prints the str of whatever you give it—although with a list, the str is identical to the repr; they're both effectively '[' + ', '.join(map(repr, self)) + ']').


Second, you could use a format that's designed for data persistent, like JSON:

>>> json.dumps(a)
'[[1, 2, "hello"], [3, 5, "hi There"], [5, 7, "I don\'t know"]]'

Third, you can join together the repr of each element of a in some way of your choosing, which is trivial with a map or a comprehension. For example:

>>> '[' + ', '.join(map(repr, a)) + ']'
'[[1, 2, \'hello\'], [3, 5, \'hi There\'], [5, 7, "I don\'t know"]]'

… or …

>>> 'My stuff includes: ' + ','.join(map(repr, a)) + '\n'
'My stuff includes: [1, 2, \'hello\'],[3, 5, \'hi There\'],[5, 7, "I don\'t know"]\n'

Or you can do the same thing recursively.

Or you can flatten the list (e.g., flatten it one step with itertools.chain, or recursively with the recipes from the itertools docs or with the more-itertools package) and then stringify the pieces however you want and then join them up.

Or you can just write the word LIST.

All of those are perfectly valid things to pass to write.

3

List comprehension would be the best choice:

>>> ''.join([str(item) for sublist in a for item in sublist])
"12hello35hi There57I don't know"

It's the most recommended approach in a similar SO question, considering performance and syntax.

1

I was looking for an answer to this as well. After reading the comments here, this is what I came up with:

I was looking for an answer to this as well. After reading the comments here, this is what I came up with:

','.join(str(' '.join(str(x) for x in v)) for v in a)

This creates something like:

1 2 hello,3 5 hi There,5 7 I don't know

If you want all spaces as delimiters, then use ' ' instead of ',' at the front.

0

What about using itertools?

from itertools import chain
doc.write(''.join(map(str, chain(a))))

Alternatively:

doc.write(''.join(str(i) for sub_list in a for i in sub_list))

You suggested a using a for loop. You could indeed do this, although the options above are probably better.

new_a = []
for sub_list in a:
    for i in sublist:
        new_a.append(str(i))
doc.write(''.join(new_a))

This is basically the previous option, but unrolled.

Unless you want to just write the first list, in which case you could do this:

doc.write(''.join(map(str, a[0])))
0
0

It's difficult for me to be sure, because your question is too short, but it seems to me that you are in a XY problem, that is to say :
you ask a question about a Y problem that you think of as being the one that needs to be solved to goes out of an uphill X problem. But your real problem is that you think that the Y problem is the way to answer to the real problem X AND that you present here only the Y problem.
Writing that, I only paraphrase what is said here: XY problem

If I am right, my opinion is that you will have a better way to solve your real X problem using one of the following tools, that allow to serialize an object and to record the serialized object in a file:

pickle

marshal

shelve

I won't paraphrase and repeat all is the docs on these tools, read them.

.

If i am wrong and that you really just want to write an object under the form of a string representation, you can also do:

from pprint import pformat

a = [[1, 2, "hello"],
     [3, 5, "hi There"],
     [5,7,"I don't know"]]

with open('doc.txt','w') as f:
    f.write(pformat(a,width=12))
14
  • This is more of a comment than an answer.
    – abarnert
    Oct 31, 2013 at 23:09
  • I don't think this is helpful. The OP isn't asking about how to do something wrongly (e.g. parse XML with regex), but a reasonable question. The modules you have given aren't very helpful in terms of writing to a human-readable "textfile" (my emphasis), and I believe that link-only answers are discouraged.
    – rlms
    Oct 31, 2013 at 23:11
  • @abarnert I habitually appreciate your answers and comments, but presently I don't understand this comment of yours. It seems to me that the crucial point is: am I right when thinking that the OP tries to find a way to apply a wrong solution to his problem instead of finding a real good and adapted soulution. If yes my advice, that answers to his X problem instead of answering to the Y pseudo-solution, deserves as much an answer format as the other answers, in my opinion.
    – eyquem
    Oct 31, 2013 at 23:38
  • @sweeneyrod Where do you see allusions to XML and regex in the question and in my answer ?????
    – eyquem
    Oct 31, 2013 at 23:44
  • 1
    Explaining why the question is not a good question is not an answer. Any answer that roughly matches one of the standard close reasons is not an answer. Even if it were, a list of links with no commentary is not an answer. So, this is not an answer. (That being said, whoever downvoted your answer should probably have flagged it as "Not an Answer" instead, as explained here.)
    – abarnert
    Nov 1, 2013 at 2:12
0

You can also just use a simple list comprehension like this:

doc.write([x for x in i for i in a])

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.