根据 txt/csv 文件 (Python) 中的两个值计算增长百分比
Calculate the percentage growth from two values in a txt/csv file (Python)
我有一个文件 "Dow.txt"
格式如下:name, symbol, exchange, industry, value0, value1, value2, value3
道琼斯工业平均指数中的 30 只股票。
我如何确定 2013 年在百分比增长方面表现最好和最差的股票?可能的结果如下图:
Best performing stock: stock name, percentage of growth
Worst performing stock: stock name, percentage of growth
我不知道如何让程序知道哪个是开始价格,哪个是结束价格,所以我不知道如何开始计算。
所以任务是:
- 读取文件
- 获取列的值
- 计算百分比差异
- 输出结果
文件link如下:
https://drive.google.com/file/d/107pPSYgSrjEVdqR7QZW1W2l6QP8n-18g/view?usp=sharing
这是一种不使用任何导入的可能解决方案:
def lines(file: str):
with open(file) as f:
for line in f:
yield line
def parse(lines):
for line in lines:
yield line.split(",")
def get_percentage_growth(path):
line = lines(path)
best = {"name": None, "percentage": float('-inf')}
worst = {"name": None, "percentage": float('inf')}
for row in parse(line):
first, second = float(row[4]), float(row[5])
percentage = (second-first)/first * 100
if percentage > best["percentage"]:
best["name"] = row[0]
best["percentage"] = percentage
if percentage < worst["percentage"]:
worst["name"] = row[0]
worst["percentage"] = percentage
return best, worst
if __name__ == '__main__':
f = "data.txt"
b, w = get_percentage_growth(f)
print(f'Best performing stock: {b["name"]}, {b["percentage"]}')
print(f'Worst performing stock: {w["name"]}, {w["percentage"]}')
假设 python 文件与 data.txt 文件位于同一目录中,这应该可行。好处是由于生成器的原因,这种方法可以处理TB的文件。
我有一个文件 "Dow.txt"
格式如下:name, symbol, exchange, industry, value0, value1, value2, value3
道琼斯工业平均指数中的 30 只股票。
我如何确定 2013 年在百分比增长方面表现最好和最差的股票?可能的结果如下图:
Best performing stock: stock name, percentage of growth
Worst performing stock: stock name, percentage of growth
我不知道如何让程序知道哪个是开始价格,哪个是结束价格,所以我不知道如何开始计算。
所以任务是:
- 读取文件
- 获取列的值
- 计算百分比差异
- 输出结果
文件link如下: https://drive.google.com/file/d/107pPSYgSrjEVdqR7QZW1W2l6QP8n-18g/view?usp=sharing
这是一种不使用任何导入的可能解决方案:
def lines(file: str):
with open(file) as f:
for line in f:
yield line
def parse(lines):
for line in lines:
yield line.split(",")
def get_percentage_growth(path):
line = lines(path)
best = {"name": None, "percentage": float('-inf')}
worst = {"name": None, "percentage": float('inf')}
for row in parse(line):
first, second = float(row[4]), float(row[5])
percentage = (second-first)/first * 100
if percentage > best["percentage"]:
best["name"] = row[0]
best["percentage"] = percentage
if percentage < worst["percentage"]:
worst["name"] = row[0]
worst["percentage"] = percentage
return best, worst
if __name__ == '__main__':
f = "data.txt"
b, w = get_percentage_growth(f)
print(f'Best performing stock: {b["name"]}, {b["percentage"]}')
print(f'Worst performing stock: {w["name"]}, {w["percentage"]}')
假设 python 文件与 data.txt 文件位于同一目录中,这应该可行。好处是由于生成器的原因,这种方法可以处理TB的文件。