小编ran*_*bar的帖子

将元组列表写入 txt 文件时对齐文本

我正在尝试将元组列表写入 txt 文件并将其与左侧对齐。(需要用制表符分隔)这是元组列表:

list1 = [(1, "Banana", "Yellow"), (2 , "Apple", "Red"), (3, "Carrot", "Orange")]
Run Code Online (Sandbox Code Playgroud)

这是我写的代码:

def write_fruit(list1,new_file):
if not isinstance(list1, list):
    raise ValueError("First input must be a list.")
header = "Num Fruit Color"
with open(new_file, "w") as output:
    output.write(header + "\n")
    for line in list1:
        if not isinstance(line[1], str):
            raise ValueError("Second input must be a str.")
        vals = " ".join(str(i) for i in line)
        output.write(vals + "\n")
print(write_fruit(fruit_list, "fruit_list.txt"))
Run Code Online (Sandbox Code Playgroud)

我的 txt 文件如下所示:

Num  Fruit  Color
 1  Banana    Yellow
 2 …
Run Code Online (Sandbox Code Playgroud)

python tuples function list

1
推荐指数
1
解决办法
43
查看次数

标签 统计

function ×1

list ×1

python ×1

tuples ×1