print two dimensional list

后端 未结 7 2505
[愿得一人]
[愿得一人] 2021-02-20 14:46

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\"]]
         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 15:25

    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])))
    

提交回复
热议问题