嗨,我想从我的列表中删除删除换行符,并获得每个元素的第三个单词。我使用的是split和rstrip。这是我的代码:
# obtain just compound ids from list
just_compound_id = []
for line in final_list:
split_file = line.split(' ')
split_file = line.rstrip()
just_compound_id.append(split_file[2])
print(just_compound_id)但是我得到了一个非常奇怪的输出,如下所示
['I']
['I', 'I']
['I', 'I', 'I']
['I', 'I', 'I', 'I']
['I', 'I', 'I', 'I', 'I']**编辑
这是我的输入
['UNIQUE-ID - ASN\n', 'UNIQUE-ID - D-GLT\n', 'UNIQUE-ID - 4-AMINO-
BUTYRATE\n', 'UNIQUE-ID - CPD-8569\n', 'UNIQUE-ID - CPD-17095\n', 'UNIQUE-ID
- CPD-17880\n', 'UNIQUE-ID - GLY\n', 'UNIQUE-ID - CPD-18298\n', 'UNIQUE-ID -
D-SERINE\n', 'UNIQUE-ID - ACETYLCHOLINE\n', 'UNIQUE-ID - DOPAMINE\n',
'UNIQUE-ID - SEROTONIN\n', 'UNIQUE-ID - HISTAMINE\n', 'UNIQUE-ID -
PHENYLETHYLAMINE\n', 'UNIQUE-ID - TYRAMINE\n', 'UNIQUE-ID - CPD-58\n',
'UNIQUE-ID - 1-4-HYDROXYPHENYL-2-METHYLAMINOETHAN\n', 'UNIQUE-ID -
TRYPTAMINE\n']发布于 2017-10-20 10:10:16
它应该是split_file.split(' ')而不是line.split(' '),而且您还需要在line.rstrip()之前执行split_file.split(' ')
just_compound_id = []
for line in final_list:
split_file = line.rstrip()
split_file = split_file.split(' ')
just_compound_id.append(split_file[2])
print(just_compound_id)按照目前的方式,对split_file的第一个赋值不起作用,因为您不使用它,并在下一个赋值中覆盖它。
发布于 2017-10-20 10:17:13
您可以使用列表理解:
[e.rstrip().split('-')[2] for e in finallist]发布于 2017-10-20 10:22:00
如果您有更复杂的输入,另一个选择是regex。对于上面的情况,我建议使用-拆分行并设置maxsplit参数。
final_list = ['UNIQUE-ID - ASN\n', 'UNIQUE-ID - D-GLT\n', 'UNIQUE-ID - 4-AMINO-BUTYRATE\n', 'UNIQUE-ID - CPD-8569\n', 'UNIQUE-ID - CPD-17095\n', 'UNIQUE-ID - CPD-17880\n', 'UNIQUE-ID - GLY\n', 'UNIQUE-ID - CPD-18298\n', 'UNIQUE-ID - D-SERINE\n', 'UNIQUE-ID - ACETYLCHOLINE\n',
'UNIQUE-ID - DOPAMINE\n', 'UNIQUE-ID - SEROTONIN\n', 'UNIQUE-ID - HISTAMINE\n', 'UNIQUE-ID - PHENYLETHYLAMINE\n', 'UNIQUE-ID - TYRAMINE\n', 'UNIQUE-ID - CPD-58\n', 'UNIQUE-ID - 1-4-HYDROXYPHENYL-2-METHYLAMINOETHAN\n', 'UNIQUE-ID - TRYPTAMINE\n']
just_compound_id = []
for line in final_list:
line = line.rstrip()
split_id = line.split('-', 2)[2].strip()
just_compound_id.append(split_id)
print(just_compound_id)https://stackoverflow.com/questions/46841300
复制相似问题