简体   繁体   中英

Python how to remove brackets when printing a list of tuples?

How do I remove the brackets from this tuple output: [("fred's", 13), ("jack's", 19), ("mark's", 16), ("amy's", 12), ("finlay's", 17)].

This is the code I used to output the tuple:

    file_path = "test.txt"
with open(file_path, 'r') as f:
    file_lines = f.readlines() 
names_and_scores = [(l.strip().split(' ')[0], int(l.strip().split(' ')[2])) for l in file_lines]
names_and_scores.sort(key=lambda x: x[1], reverse=True)
print(names_and_scores[:5])

Maybe something like this?

print ("".join(str(names_and_scores[:5])).strip("()"))

names_and_scores[:5] is a list of tuples, which is why you see the brackets around the output. To remove the brackets you can convert the list to a string by comma separating all of the individual tuple elements in the list:

", ".join(names_and_scores[:5])

You're kind of misunderstanding. In general, you can never remove characters from a tuple. Since they are immutable, you can only create a new one and build it using the desired elements of the original. The reason there are square brackets is because the output of your "names and scores" was created using list comprehension. That is to say, it's a list. The square brackets are there to tell you it's a list, so you can't "remove them". If you want to see each tuple without the square brackets you can iterate through the list of tuples and print each tuple. That way you'd get something like:

("Fred's", 13)
("Jack's", 12)

If you want to remove the brackets round and square, you can refer to the tuple with indexes for the values. You can do:

print("PLAYER:\t\tSCORE:")
for i in names_and_scores[:5]:
    print("{}\t\t{}".format(i[0],i[1]))

This is going to iterate through the desired portion of your list (up till the fifth, it seems) and then print something like...

PLAYER:    SCORE:
Jack's     12
Fred's     13

You can ignore the 's with...

print("PLAYER:\t\tSCORE:")
    for i in names_and_scores[:5]:
        print("{}\t\t{}".format(i[0][:-2],i[1]))

Here's my code and output:

list = [("fred's", 13), ("jack's", 19), ("mark's", 16), ("amy's", 12), ("finlay's", 17)]
print("PLAYER:\t\tSCORE")
for i in list:
        print("{}\t\t{}".format(i[0][:-2],i[1]))



PLAYER:         SCORE
fred            13
jack            19
mark            16
amy             12
finlay          17

The easiest way that i can think of is to iterate through the list

list=[("fred's", 13), ("jack's", 19), ("mark's", 16), ("amy's", 12), ("finlay's", 17)]
for item in list:
    name,number=item
    print(name,number)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM