Skip to main content
 首页 » 编程设计

python之如何返回格式化的元组列表

2025年05月04日15mengfanrong

我有一个元组列表。我想从类中重写的 str 返回它们。我可以设置它们的格式,以便在打印类(class)时,它们将一个元组堆叠在另一个元组之上吗?

示例代码:

class bar: 
    tuplist = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] 
    def __str__(self): 
        return 'here are my tuples: ' + '\n' + str(self.tuplist) 
 
foo = bar() 
print(foo) 

上面的代码打印:

here are my tuples:  
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] 

但我想让它打印:

('a', 'b') 
('c', 'd') 
('e', 'f') 
('g', 'h') 

我不会总是知道元组列表有多大,我需要使用覆盖的 str 进行格式化。这可能吗?我该怎么做?

请您参考如下方法:

您可以使用换行符加入元组列表:

class bar: 
    tuplist = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] 
    def __str__(self): 
        return 'here are my tuples: ' + '\n' + "\n".join(map(str, self.tuplist)) 
​ 
foo = bar() 
print(foo) 
 
here are my tuples:  
('a', 'b') 
('c', 'd') 
('e', 'f') 
('g', 'h')