plapapyjh 2022-09-23 17:27 采纳率: 43.5%
浏览 33
已结题

Python初学者遇到的基础问题

这个代码没有问题,主要就是将txt文件中内容,每行以列表等不同形式输出,现在要将读取代码数据操作并将其处理到parts变量中,但将数据作为列表,在get_data函数 列表执行此修改,return 出[['CP1401', 'Ada Lovelace', 192],['CP1404', 'Alan Turing', 98]]这种

FILENAME = "subject_data.txt"


def main():
    data = get_data()
    print(data)


def get_data():
    """Read data from file formatted like: subject,lecturer,number of students."""
    input_file = open(FILENAME)

    for line in input_file:
        print(line)  # See what a line looks like
        print(repr(line))  # See what a line really looks like
        line = line.strip()  # Remove the \n
        parts = line.split(',')  # Separate the data into its parts
        print(parts)  # See what the parts look like (notice the integer is a string)
        parts[2] = int(parts[2])  # Make the number an integer (ignore PyCharm's warning)
        print(parts)  # See if that worked
        print("----------")
    input_file.close()


main()

#txt文件内容
CP1401,Ada Lovelace,192
CP1404,Alan Turing,98
CP4321,Bill Gates,676
CP1234,Steve Jobs,123

  • 写回答

2条回答 默认 最新

  • 爱音斯坦牛 全栈领域优质创作者 2022-09-23 17:34
    关注

    代码和运行截图如下:有帮助的话记得采纳一下!

    FILENAME = "subject_data.txt"
    
    def main():
        data = get_data()
        print(data)
    
    def get_data():
        """Read data from file formatted like: subject,lecturer,number of students."""
        input_file = open(FILENAME)
        list = []
        for line in input_file:
            print(line)  # See what a line looks like
            print(repr(line))  # See what a line really looks like
            line = line.strip()  # Remove the \n
            parts = line.split(',')  # Separate the data into its parts
            print(parts)  # See what the parts look like (notice the integer is a string)
            parts[2] = int(parts[2])  # Make the number an integer (ignore PyCharm's warning)
            print(parts)  # See if that worked
            print("----------")
            list.append(parts)
        input_file.close()
        return list
    
    main()
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月1日
  • 已采纳回答 9月23日
  • 创建了问题 9月23日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来