有没有更好的pythonic方法来编写这个代码?

2024-03-29 08:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从文本文件中读取第一列和第三列,并将它们添加到一起。你知道吗

下面的代码工作得很完美,并给出了我需要的结果,但是否有更好的更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]

Tags: 文件方法代码inforcolresultpythonic
3条回答

您可以使用zip

with open('random.txt', 'r') as fn:
    next(fn)
    first_col, _, third_col  = [
        *zip(*(int(x) for x in map(lambda x: x.split(','), fn))
    ]
    ...
    results = [x+y for x, y in zip(first_col, second_col)]

或者如果你不需要抱着驴:

results = [
    x+y for x, _, y in zip(*(int(x) for x in map(lambda x: x.split(','), fn))
]

我想说最简单的方法就是坚持基本原则,没有正确的方法!你可以让你的代码变得简单和复杂。你知道吗

import csv

res = []
with open('file.txt', 'r') as fp:
    #Open csv file
    reader = csv.reader(fp)
    next(reader)
    #Iterate through rows and append the sum of first and third rows to a list
    for row in reader:
        res.append(int(row[0]) + int(row[2]))

print(res)
#[122, 153, 74]

如果您可以使用numpy,那么我的建议是使用^{}函数:

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

相关问题 更多 >