[Python] Simplify formatting and printing elements of a nested list on the same line

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list which contains 3 lists of two strings each as given below:

    final_hands = [["Ace of Hearts", "King of Clubs"], ["5 of Diamonds", "6 of Spades"], ["Queen of Clubs", "Jack of Hearts"]]

    When I print this list, I want it to look like this:

    [Ace of Hearts, King of Clubs], [5 of Diamonds, 6 of Spades], [Queen of Clubs, Jack of Hearts]


    I achieved the desired output using the following code:

    final_hands = [["Ace of Hearts", "King of Clubs"], ["5 of Diamonds", "6 of Spades"], ["Queen of Clubs", "Jack of Hearts"]]

    card_list = []
    for i in range(len(final_hands)):
    card_list.append(f"[{", ".join(final_hands)}]")
    print(", ".join(card_list), sep = ", ")


    I then converted the above code onto a single line

    print(", ".join(f"[{", ".join(final_hands)}]" for i in range(len(final_hands))), sep = ", ") and this works as well.

    However, I was wondering if there's a more elegant way of doing this? I've just started learning Python and this code seems rather clumsy to me; when I come back to this 6 months from now, I will never be able to understand what I did.

    Continue reading...

Compartilhe esta Página