如何拆分列表?

时间:2014-08-15 22:00:22

标签: python list split indexing indices

我正在获取一个列表,例如

StudentStatus = ['Physics Pass', 'Chem Distinction', 'Maths Average']

我正在打印它:

for each in StudentStatus:
    print each

因此输出

Physics Pass
Chem Distinction
Maths Average

我想用另一种方式打印它。 我试过了 -

for each in StudentStatus:
    print each[0], each[1]

刚刚印刷

Physics
Chem
Maths

如何拆分列表以获得正确的输出?

2 个答案:

答案 0 :(得分:0)

假设最后一个单词是成绩,那么您可以使用str.rpartition

StudentStatus = ['Physics Pass', 'Chem Distinction', 'Maths Average']

for item in StudentStatus:
    print 'Subject: {0} - Grade: {2}'.format(*item.rpartition(' '))

输出:

Subject: Physics - Grade: Pass
Subject: Chem - Grade: Distinction
Subject: Maths - Grade: Average

答案 1 :(得分:0)

StudentStatus = ['Physics Pass', 'Chem Distinction', 'Maths Average']
for echo in StudentStatus:
    first, second = echo.split()
    print first, second