Nabodita Gangully
Nabodita Gangully

Reputation: 1

Simplify formatting and printing elements of a nested list

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[i])}]")
print(", ".join(card_list), sep = ", ")

I tried to convert the above code onto a single line:

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

and this worksm but seems unnecessarily complicated and is not easy to read.

Can anyone suggest an alternative way to achieve the same result in a single statement or using fewer lines of code?

Upvotes: -4

Views: 54

Answers (1)

Adon Bilivit
Adon Bilivit

Reputation: 27211

Build a list of strings based on each element of the input list then join on ", " for printing

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

output = [f"[{a}, {b}]" for a, b in final_hands]

print(", ".join(output))

Output:

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

Upvotes: 1

Related Questions