如何拆分列表中的部分?

时间:2014-12-02 20:28:34

标签: python list

好的,所以我有一个名为名单的列表,列表中还有其他单词,但这是名称的结果[0]

Chen,David,M,334791530,,11Z,,16770712,,,,,,00015956753,
Chen,Peter,M,321564726,,11B,,19979810,,,,,,00012446698,
Chung,Rowan,M,32355988,,11T,,17890708,,,,,,00012127821,
Chung,Kyle,M,387638355,,10U,,19970317,,,,,,00015604870,
Fan,Mark,M,34217543,,10U,,19707713,,,,,,00015799079,

如何拆分名称[0],使其仅显示姓氏,名字和性别?

这是我的其余代码:

file = open('CASS.txt', 'r')
f = file.readlines()
file.close()
for line in f:
    if line.find('ICS3M105')>=0:
        names = line.split()
        for name in names[0]:
            if name in range(0,1):
                print(names)

3 个答案:

答案 0 :(得分:1)

for line in f:
  names = line.split()
  print names[0].split(',')[0:3]

答案 1 :(得分:1)

with open('CASS.txt', 'r') as f:
    for line in f:
        name_last, name_first, gender = line.split(',')[0:3]

或者使用csv模块,这可能对即将到来的任务更可靠

import csv
with open('CASS.txt', 'r') as f:
    for row in csv.reader(f):
        name_last, name_first, gender = row[0:3]

答案 2 :(得分:0)

>>> s = """Chen,David,M,334791530,,11Z,,16770712,,,,,,00015956753,
           Chen,Peter,M,321564726,,11B,,19979810,,,,,,00012446698,
           Chung,Rowan,M,32355988,,11T,,17890708,,,,,,00012127821,
           Chung,Kyle,M,387638355,,10U,,19970317,,,,,,00015604870,
           Fan,Mark,M,34217543,,10U,,19707713,,,,,,00015799079,"""

您可以使用列表推导来分割逗号,然后使用切片将元素[0]索引到[2]操作的split(包括)。

>>> [i.split(',')[:3] for i in s.split('\n')]
[['Chen', 'David', 'M'],
 ['Chen', 'Peter', 'M'],
 ['Chung', 'Rowan', 'M'],
 ['Chung', 'Kyle', 'M'],
 ['Fan', 'Mark', 'M']]