python - 输出格式 Python 3.3

标签 python python-3.x output-formatting

所以这可能是一个关于在 python 中使用“.format”进行输出格式化的非常基本的问题,因为我是初学者,所以我一辈子都弄不明白。我试图尽可能详细,只是为了确保没有混淆。

让我举个例子,让你更好地理解我的困境。考虑以下程序

list = (['wer', 'werwe', 'werwe' ,'wer we'])   # list[0], list[1], list[2], list[3]
list.append(['vbcv', 'cvnc', 'bnfhn', 'mjyh']) # list[4]
list.append(['yth', 'rnhn', 'mjyu', 'mujym'])  # list[5]
list.append(['cxzz', 'bncz', 'nhrt', 'qweq'])  # list[6]

first = 'bill'
last = 'gates'

print ('{:10} {:10} {:10} {:10}'.format(first,last,list[5], list[6]))     

可以理解,这会给出输出:

bill       gates      ['yth', 'rnhn', 'mjyu', 'mujym'] ['cxzz', 'bncz', 'nhrt', 'qweq']

所以这是我真正的问题。我正在做这本书中的练习题,但我不明白答案。下面的程序会让你很好地了解我们想要什么样的输出:

students = []
students.append(['DeMoines', 'Jim', 'Sophomore', 3.45]) #students[0]
students.append(['Pierre', 'Sophie', 'Sophomore', 4.0]) #students[1]
students.append(['Columbus', 'Maria', 'Senior', 2.5])   #students[2]
students.append(['Phoenix', 'River', 'Junior', 2.45])   #students[3]
students.append(['Olympis', 'Edgar',  'Junior', 3.99])  #students[4]
students.append(['van','john', 'junior', 3.56])         #students[5]
def Grades(students):
    print ('Last       First      Standing        GPA')
    for students in students:
        print('{0:10} {1:10} {2:10} {3:8.2f}'.format(students[0],students[1],students[2],students[3]))

我们试图获得的输出是一种表格,其中提供了所有学生的所有统计信息 -

Last       First      Standing        GPA
DeMoines   Jim        Sophomore      3.45
Pierre     Sophie     Sophomore      4.00
Columbus   Maria      Senior         2.50
Phoenix    River      Junior         2.45
Olympis    Edgar      Junior         3.99
van        john       junior         3.56

所以这就是我不明白的地方。在这两个示例中,我们使用的是基本相同的东西,即列表中的列表。对于我的第一个例子,打印语句是:

print('{:10} {:10} {:10} {:10}'.format(first, last, list[5], list[6]))  

其中 list[5]list[6] 是列表本身,它们是完整打印的,正如您从输出中看到的那样。 但这不会发生在书的问题上。在那里,打印语句说

print('{0:10} {1:10} {2:10} {3:8.2f}'.format(students[0], students[1], students[2], students[3])) 

从表输出中可以看出,这里的 students[0] 仅指 'DeMoines'。但是,如果您只是在 Python 解释器中运行语句 students[0],它会给出整个子列表,这是应该的。

['DeMoines', 'Jim', 'Sophomore', 3.45]

所以,基本上,我有两个问题,为什么 students[0] 有两个不同的含义,为什么 students[0] 不打印整个列表就像我们对 list[5]list[6] 所做的那样?

最佳答案

看看 for 循环:

for students in students:
#   ^^^^^^^^

因此,students(内部循环)实际上并不是指list of list。正如预期的那样,students[0] 引用list of listselementfirst element

我建议用 all_students 或类似的东西替换函数参数中的 students

关于python - 输出格式 Python 3.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16815170/

相关文章:

python - 适用于多个操作系统的 Matplotlib 后端?

Python 从包中安装子包

python - 如何在 Python 中对 Active Directory 服务器进行两阶段身份验证?

python - 这个三元运算符有什么问题?

python-3.x - 如何在kivy中获取 "mouse over"事件

c - 打印多维字符数组

r - 打印数据框时不打印NA

perl - 更新命令行输出

python - os.walk() 没有获取我的文件名

python-3.x - PySpark - py4j.protocol.Py4JJavaError,在我的 win10 笔记本电脑上运行 Spark 线性回归模型时