Home > Net >  How do I format a two dimensional list to print it a specific way
How do I format a two dimensional list to print it a specific way

Time:09-07

    lst = [[1,2,3], [2,3,4], [3,4,5], [4]]

how would I format this so that I could print something that looks like this:

    1: [2 3] 
    2: [3 4]
    3: [4 5]
    4: []

Any type of advice or hints would be much appreciated.

CodePudding user response:

Iterate through your list and unpack the elements, printing each one:

for a, *b in mylist:
    print(f"{a}: {b}")

CodePudding user response:

Use the * operator:

lst = [[1,2,3], [2,3,4], [3,4,5], [4]]

for (head, *tail) in lst:
    print(f"{head}: {tail}")

Output:

1: [2, 3]
2: [3, 4]
3: [4, 5]
4: []

CodePudding user response:

Use the * operator to split each list into its first element and the remainder, and str.join to format the remainder without the commas.

>>> lst = [[1,2,3], [2,3,4], [3,4,5], [4]]
>>> for i, *j in lst:
...     print(f"{i}: [{' '.join(str(n) for n in j)}]")
...
1: [2 3]
2: [3 4]
3: [4 5]
4: []

CodePudding user response:

A inline solution because we love them:

lst = [[1,2,3], [2,3,4], [3,4,5], [4]]

[print(f"{element[0]}: {element[1:]}") for element in lst]

Outputs:

1: [2, 3]
2: [3, 4]
3: [4, 5]
4: []

Or even smaller and inline:


[print(f"{a}: {b}") for a, *b in lst]

Outputs:

1: [2, 3]
2: [3, 4]
3: [4, 5]
4: []

Note this is equivalent to which doesn't uses print in a list comprehension:

for a, *b in lst: print(f"{a}: {b}")
  • Related