简体   繁体   English

从文件中读取列表,然后循环编写以求解数学方程式

[英]Reading a list from file, then writing in a loop to solve for math equation

I have a list in a file that is made up of numbers. 我在由数字组成的文件中有一个列表。

I have a command to read the number in the list: 我有一个命令可以读取列表中的数字:

But I am having error: 但是我有错误:

TypeError: 'int' object is not subscriptable

Which I don't understand what 'int' is an issue. 我不明白什么是“ int”是一个问题。

with open('angles.txt', 'r') as f:
    print('Angle Sine         Cosine      Tangent')

    for number in f:
        degree= int(number)
        rad = math.radians(degree)
        sin = math.sin(rad)

        answer = degree[0]
        print(str(answer), end = '')

        print(format(math.sin(math.radians(rad)),'10.5f'),end='')
        print(format(math.cos(math.radians(rad)),'10.5f'),end='')
        print(format(math.tan(math.radians(rad)),'10.5f'),end='')

I can answer your specific question about the int type error. 我可以回答您有关int类型错误的具体问题。 The problem is that these two lines don't make sense to python: 问题是这两行对python没有意义:

degree = int(number)

answer = degree[0]

You're first defining degree to be an integer, and then trying to access that integer like a list! 您首先将degree定义为整数,然后尝试像列表一样访问该整数! That doesn't work. 那不行

Here is a somewhat cleaned-up version (this assumes a single angle per line): 这是一个经过清理的版本(假设每行有一个角度):

import math

print('Angle         Sine     Cosine    Tangent')
with open('angles.txt') as f:
    for line in f:
        degrees = float(line)
        radians = math.radians(degrees)
        print(
            "{:5.1f}   {:10.5f} {:10.5f} {:10.5f}"
            .format(degrees, math.sin(radians), math.cos(radians), math.tan(radians))
        )

which produces something like: 会产生类似:

Angle         Sine     Cosine    Tangent
  0.0      0.00000    1.00000    0.00000
 10.0      0.17365    0.98481    0.17633
 20.0      0.34202    0.93969    0.36397
 30.0      0.50000    0.86603    0.57735
 40.0      0.64279    0.76604    0.83910
 50.0      0.76604    0.64279    1.19175
 60.0      0.86603    0.50000    1.73205
 70.0      0.93969    0.34202    2.74748
 80.0      0.98481    0.17365    5.67128

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM