-2

Is there a way to add a line break in the result of a sorted applied to a list of tuples ?

my list of tuples :

b1 = ("&#20843", 222, 133, 343)
b1a = ("&#20023", 3001, 61, 0)
b2 = ("&#24052", 610, 33, 281)
b3 = ("&#30333", 287, 70, 838)
b4 = ("&#30334", 226, 13, 383)
b5 = ("&#21150", 323, 3, 279)
b6 = ("&#21322", 374, 21, 495)
b6a = ("&#21241", 3001, 46, 1)
b6b = ("&#21253", 417, 37, 471)
b7 = ("&#36125", 1424, 137, 60)
b8 = ("&#26412", 76, 11, 856)

hanzi = [b1, b1a, b2, b3, b4, b5, b6, b6a, b6b, b7, b8]

I apply a sorted to sort the tuples :

print(sorted(hanzi, key=lambda hanzi: hanzi[2])

The result is a list of tuples :

[('&#21150', 323, 3, 279), ('&#26412', 76, 11, 856), ('&#30334', 226, 13, 383), ('&#21322', 374, 21, 495), ('&#24052', 610, 33, 281), ('&#21253', 417, 37, 471), ('&#21241', 3001, 46, 1), ('&#20023', 3001, 61, 0), ('&#30333', 287, 70, 838), ('&#20843', 222, 133, 343), ('&#36125', 1424, 137, 60)]

I want them in a column like below :
[('&#21150', 323, 3, 279),
('&#26412', 76, 11, 856),
('&#30334', 226, 13, 383),
('&#21322', 374, 21, 495),
('&#24052', 610, 33, 281),
('&#21253', 417, 37, 471),
('&#21241', 3001, 46, 1),
('&#20023', 3001, 61, 0),
('&#30333', 287, 70, 838),
('&#20843', 222, 133, 343),
('&#36125', 1424, 137, 60)]

I am a beginner with python, don't know where add '/n' :-) Even don't know if is possible ! do i have to modify the tuples themselve ?

Ilia Kurenkov
  • 637
  • 5
  • 12
seeeerge
  • 7
  • 1
  • 6

4 Answers4

2

If you just want one tuple per line, then you can join the reprs with a newline:

result = sorted(hanzi, key=lambda hanzi: hanzi[2])
print("\n".join(repr(x) for x in result))

Or, with sep:

result = sorted(hanzi, key=lambda hanzi: hanzi[2])
print(*result, sep="\n")

If you want the list syntax (starts with [, has commas between, and ends with ]), then you can join on ,\n instead and manually add the [] in:

result = sorted(hanzi, key=lambda hanzi: hanzi[2])
print("[" + ",\n".join(repr(x) for x in result) + "]")
Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

You can use pprint

from pprint import pprint
pprint(sorted(hanzi, key=lambda hanzi: hanzi[2]))

Vaebhav
  • 4,672
  • 1
  • 13
  • 33
1

You can do something like this:

your_list = sorted(hanzi, key=lambda hanzi: hanzi[2])
print(str(your_list).replace("),", "),\n"))
Jarvis
  • 8,494
  • 3
  • 27
  • 58
1
for item in sorted(hanzi, key=lambda hanzi: hanzi[2]):
    print(item)

Output:

('&#21150', 323, 3, 279)
('&#26412', 76, 11, 856)
('&#30334', 226, 13, 383)
('&#21322', 374, 21, 495)
('&#24052', 610, 33, 281)
('&#21253', 417, 37, 471)
('&#21241', 3001, 46, 1)
('&#20023', 3001, 61, 0)
('&#30333', 287, 70, 838)
('&#20843', 222, 133, 343)
('&#36125', 1424, 137, 60)
klv0000
  • 174
  • 10