Skip to main content
 首页 » 编程设计

python之有没有更好的 pythonic 方式来编写这段代码

2025年05月04日9zhujiabin

我正在尝试从文本文件中读取第一列和第三列并将它们相加。

下面的代码完美运行并给出了我需要的结果,但我想知道是否有更好的 pythonic 方式来编写它?

with open('random.txt', 'r') as fn: 
    next(fn) 
    numbers = fn.readlines() 
    first_col = [int(x.split(',')[0]) for x in numbers] 
    third_col = [int(y.split(',')[2]) for y in numbers] 
 
    result = [v + z for v, z in zip(first_col, third_col)] 
 
    print(result) 

随机文件就是字面上的随机文件。

col1,col2,col3 
44,65,78 
55,87,98 
12,32,62 

结果:

[122, 153, 74] 

请您参考如下方法:

如果你可以使用 numpy 那么我的建议是使用 loadtxt功能:

import numpy as np 
np.loadtxt('random.txt', dtype=int, skiprows=1, delimiter=',', usecols=(0, 2)).sum(axis=1).tolist()