Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.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_Tuples - Fatal编程技术网

Python 我想将当前的元组列表设置为两列格式,但第一行作为标题

Python 我想将当前的元组列表设置为两列格式,但第一行作为标题,python,tuples,Python,Tuples,我让这段代码遍历我的原始文件,读取并创建元组列表 def initialize_portfolio(filename): port_list = [] with open("holdings.txt") as filename: for line in filename: # strip removes all leading and trailing spaces line = line.st

我让这段代码遍历我的原始文件,读取并创建元组列表

def initialize_portfolio(filename):

    port_list = []
    with open("holdings.txt") as filename:
        for line in filename:
            # strip removes all leading and trailing spaces
            line = line.strip()
            # skip empty lines
            if not line:
                continue
            # use partition to split the entries
            a, _, b = line.partition(',')
            a = a.strip()
            b = int(b.strip())
            # create a tuple while appending
            port_list.append((a, b))

    return port_list
我想获取这个列表,并使用def print_公文包函数,将我上面制作的列表打印成两列格式,包括第一行标题

Symbol         Amount
BB             1000
TIS         8574
LIG         1333
etc...         etc...
etc...
portfolio=我在第一个函数中创建的元组列表

我希望函数是

def print_portfolio(portfolio): 
只需将元组组织为两列


请不要使用字典打印标题,然后循环打印每一行

def print_portfolio(portfolio):
    print("Symbol Amount")
    for symbol, amt in portfolio:
        print(symbol, amt)
如果希望列对齐,请使用格式化方法指定列宽:

def print_portfolio(portfolio):
    print("Symbol Amount")
    for symbol, amt in portfolio:
        print(f"{symbol:6} {amt:6}")

有什么问题吗?只需使用
for
循环遍历列表并打印两个元组元素。嘿@Barmar我想以一种方式打印它,将其格式化为两列,并带有标题。首先打印标题,然后循环并打印行。
打印(x[0],x[1])
将在两列中打印元组
x
。如何将格式如下的列表[(BB,1000),(TIS,8574)等]打印到两列中?