Skip to main content
 首页 » 编程设计

python之如何将字符串彼此放在一起并为其分配一个数字

2025年05月04日25hnrainll

我要改造这个

A,B                    
AFD,DNGS,SGDH          
NHYG,QHD,lkd,uyete     
AFD,TTT 

并为每一行分配一个数字,变成这个

A 1 
B 1 
AFD 2 
DNGS 2 
SGDH 2 
NHYG 3 
QHD 3 
lkd 3 
uyete 3    
AFD 4 
TTT 4 

我怎样才能做到这一点?

我卡在了下面的代码中:

import itertools 
# open the data from the directory 
with open ( './test.txt' ) as f: 
    # Make a file named result to write your results there 
    with open ( 'result.txt' , 'w' ) as w: 
        # read each line with enumerate ( a number for each string) 
        for n , line in enumerate ( f.readlines ( ) ): 

请您参考如下方法:

您可以使用以下内容:

with open('test.txt') as f_in, open('result.txt', 'w') as f_out: 
    f_out.write('\n'.join('{} {}'.format(s, i) 
                          for i, l in enumerate(f_in, 1) 
                          for s in l.strip().split(','))) 

在上面enumerate将从输入文件返回 (index, line) 元组,索引从作为参数传递的 1 开始。然后对于每一行 strip用于删除尾随换行符,然后行是 split来自每个 ,。最后,生成器表达式输出格式为 'word index' 的字符串,这些字符串在写入输出文件之前与换行符连接在一起。

更新 如果您想打印结果而不是写入文件,您可以使用以下代码:

with open('test.txt') as f_in: 
    print '\n'.join('{} {}'.format(s, i) 
                    for i, l in enumerate(f_in, 1) 
                    for s in l.strip().split(',')) 

输出:

A 1 
B 1 
AFD 2 
DNGS 2 
SGDH 2 
NHYG 3 
QHD 3 
lkd 3 
uyete 3 
AFD 4 
TTT 4