Print list of lists in separate lines

后端 未结 6 1882
生来不讨喜
生来不讨喜 2020-12-01 10:15

I have a list of lists:

a = [[1, 3, 4], [2, 5, 7]]

I want the output in the following format:

1 3 4
2 5 7
<
6条回答
  •  没有蜡笔的小新
    2020-12-01 10:44

    Iterate through every sub-list in your original list and unpack it in the print call with *:

    a = [[1, 3, 4], [2, 5, 7]]
    for s in a:
        print(*s)
    

    The separation is by default set to ' ' so there's no need to explicitly provide it. This prints:

    1 3 4
    2 5 7
    

    In your approach you were iterating for every element in every sub-list and printing that individually. By using print(*s) you unpack the list inside the print call, this essentially translates to:

    print(1, 3, 4)  # for s = [1, 2, 3]
    print(2, 5, 7)  # for s = [2, 5, 7]
    

提交回复
热议问题