【问题标题】:Write a program to read/close the file, and display the following output编写程序来读取/关闭文件,并显示以下输出
【发布时间】:2020-01-22 13:20:02
【问题描述】:

我需要编写一个 Python 程序来读取/关闭文件(即 Stock.txt),并使用 list 的 split 方法显示以下输出。 Stock.txt中只有一行是投资者的股票投资组合,由四只股票的投资金额组成。

Stock.txt 文件的内部内容:

hsbc, 84564.24, boc, 46392.45, manulife, 34562.98, galaxy, 89321.23

我只知道如何编写相关的 Python 代码来打开以读取/关闭文件。我真的不知道我应该编写什么 Python 代码来显示作业要求我执行的以下预期输出!

我当前的代码:

infile = open("Stock.txt", 'c')
data = [line.rstrip() for line in infile]

infile.close()

但我不确定我当前的代码是否正确,因为我是 Python 初学者。

此作业的预期输出:

01234567890123456789012345678901234567890123456789

The amount invested in HSBC:       844563.24
The amount invested in BOC:        465392.46
The amount invested in MANULIFE:   345612.98
The amount invested in GALAXY:     893421.23

STOCK      PERCENTAGE
---------------------
HSBC           33.13%
BOC            18.26%
MANULIFE       13.56%
GALAXY         35.05%

Total Amount Invested: $2,548,989.91

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    我不认为我可以为你完全解决它,但我可以让你开始。

    first_line = data[0] # 'hsbc, 84564.24, boc, 46392.45, manulife, 34562.98, galaxy, 89321.23'
    real_data = first_line.split(', ') # ['hsbc', '84564.24', 'boc', '46392.45', 'manulife', '34562.98', 'galaxy', '89321.23']
    

    我们的文件中有一行,所以我们用data[0]取第一行,然后用.split(', ')拆分成一个列表。

    stock_names = real_data[::2] # ['hsbc', 'boc', 'manulife', 'galaxy']
    stock_values = real_data[1::2] # ['84564.24', '46392.45', '34562.98', '89321.23']
    

    第一行从第 0 个开始获取real_data 的每个第二个元素。 第一行从第一个开始获取real_data 的每个第二个元素。 两者都使用列表拼接语法: 列表[开始:结束:步骤] Understanding slice notation

    for name, value in zip(stock_names, stock_values):
        print(name, value)
        # perform calculations ect. 
    

    大家一起:

    infile = open("stocks.txt", 'r')
    infile.close()
    data = [line.rstrip() for line in infile]
    first_line = data[0]
    real_data = first_line.split(', ')
    stock_names = real_data[::2]
    stock_values = real_data[1::2]
    for name, value in zip(stock_names, stock_values):
        print("something")
        # perform calculations
    # Good luck :)
    

    请注意,我已将 infile.close() 移到开头,因为不需要一直打开文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2014-01-15
      • 2013-07-27
      • 1970-01-01
      • 2013-05-18
      相关资源
      最近更新 更多