0

我有一个凸轮角度和位移列表:

<Ignored header>
0   3
1   3
2   6
3   9
4   12
5   15
6   18
7   21
8   24
9   27
10  30
...

我将如何去寻找一个角度并在这个角度产生位移?

没有必要存储数据,因为在任何给定时刻我只需要这两个值。

我知道这目前不起作用,但是由于我渴望了解更多信息,因此非常感谢您简要解释为什么以及如何改进

camAngle = 140

camFile = open(camFileLoc)
for line in camFile:
    if line > 1:
        if camAngle in line:
        print line

非常感谢

劳伦

4

4 回答 4

4

你基本上有它:

camAngle = 140

# The context manager closes the file automatically when you leave the block
with open(camFileLoc, 'r') as handle:
    next(handle)  # Skips the header

    for line in handle:
        # Splits the line on the whitespace and converts each string
        # into an integer. Then, you unpack it into the two variables (a tuple)
        angle, displacement = map(int, line.split())

        if angle == camAngle:
            print displacement
            break  # Exits the `for` loop
    else:
        # We never broke out of the loop, so the angle was never found
        print 'This angle is not in the file'
于 2013-05-03T08:21:38.633 回答
3

像这样的东西:

>>> angle=5   #lets say 5 is the required angle

>>> with open("abc") as f:
    next(f)                #skip header
    for line in f:
        camangle,disp = map(int,line.split()) #convert to integers and 
                                              #store in variables

        if camangle==angle: # if it is equal to the required angle then break
            print camangle,disp
            break
...             
5 15
于 2013-05-03T08:20:29.730 回答
2

构建生成器并用于islice跳过不必要的标题行并启用为未找到设置默认值的替代方法:

from itertools import islice

with open('/path/to/your/file.txt') as fin:
    data = (map(int, line.split()) for line in islice(fin, 1, None))
    value = next( (d for a, d in data if a == 3), None) # None = default is not found

如果角度是增量的,那么您也许也可以采用基于线的方法(未经测试):

with open('/home/jon/test.txt') as fin:
    no_header = islice(fin, 1, None)
    line_no = next(islice(no_header, 0, 1), '').partition(' ')[2]
于 2013-05-03T08:31:33.653 回答
0

建立一个字典{},键为 lelt 值并为正确的值赋值

f = open('try.txt', 'r')
print f
dic = {}
for line in f:
    a, b = line.split()
    dic[a] = b

print dic


>>> {'10': '30', '1': '3', '0': '3', '3': '9', '2': '6', 
          '5': '15', '4': '12', '7': '21', '6': '18', '9': '27', '8': '24'}
于 2013-05-03T08:58:20.163 回答