【问题标题】:How to update a counter variable when reading a file in Python?在 Python 中读取文件时如何更新计数器变量?
【发布时间】:2015-09-17 03:40:39
【问题描述】:

我正在开发一个距离计算器,它应该从包含具有不同距离级别的多行的文本中读取文件。然后我应该将第一个距离与第二个距离进行比较,获取差异,然后将差异存储在一个新变量中,然后该新变量将自己与下一行进行比较,等等。这种比较应该在整个文本中发生文件直到 For 循环完成。这是我写的一些代码:

file_name = input("\nEnter name of data file: ")
text_file = open(file_name,'r')
for line in text_file:
    line = line.strip()
    rows = line.split(" ")
    latitude = float(rows[0])
    longitude = float(rows[1])
    longitude_two = longitude
    latitude_two = latitude
    distance = float(calculate_distance(latitude,longitude,latitude_two,longitude_two))
    print(distance)

文本文件非常基本,看起来像这样:

54.24525 -66.25451
66.24544 -52.32658
88.21414 -52.99985
85.32111 -49.32323

每次我运行这个循环,我的输出都是零。如果有人可以帮助我,那就太好了!

【问题讨论】:

  • lat、long、latitude_2 或 longitude_2 在 for 循环中都没有更新。
  • 进一步,打印line - 确保您实际阅读的是您认为您正在阅读的内容;)
  • 你需要读取文件:for line in read(text_file):
  • 如果我错了,请纠正我,但你不是在计算恰好相同的两对点之间的距离吗?
  • @joanne72205 如果它解决了您的问题,请务必接受答案。

标签: python for-loop counter


【解决方案1】:

正如许多人在 cmets 中指出的那样,这段代码正在杀死你。

latitude = float(rows[0])
longitude = float(rows[1])
longitude_two = longitude
latitude_two = latitude

试试这样的。

file_name = input("\nEnter name of data file: ")
text_file = open(file_name,'r')
latitude = None
longitude = None

for line in text_file:
   line = line.strip()
   rows = line.split(" ")
   latitude_two = float(rows[0])
   longitude_two = float(rows[1])
   if latitude != None:
       distance = float(calculate_distance(latitude,longitude,latitude_two,longitude_two))
       print(distance)

   longitude = longitude_two
   latitude = latitude_two

【讨论】:

  • 哇,这完全解决了所有问题!我有一种感觉,我需要一个 if 语句,但我不知道该放什么!非常感谢!
  • 你应该简单地使用if latitude:
  • 正确的@Alexander,但只是在某个点可能在赤道上的情况下添加了空值比较。
  • if latitude or longitude:?
  • 我总是把两者混为一谈。那么格林威治的平均线
猜你喜欢
  • 1970-01-01
  • 2021-09-03
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2020-09-22
  • 1970-01-01
相关资源
最近更新 更多