Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何返回元组的格式化列表?_Python_Formatting - Fatal编程技术网

Python 如何返回元组的格式化列表?

Python 如何返回元组的格式化列表?,python,formatting,Python,Formatting,我有一个元组列表。我想从类中重写的str返回它们。我是否可以格式化它们,以便在打印类时,它们将显示为一个元组叠在另一个元组上 示例代码: 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(

我有一个元组列表。我想从类中重写的str返回它们。我是否可以格式化它们,以便在打印类时,它们将显示为一个元组叠在另一个元组上

示例代码:

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')

可以使用新行字符连接元组列表:

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')