[英]How to count each occurence in a nested list and print progress into console in python?
我正在编写一个程序,它应该读取包含表示为 N、S、W、E 的坐标的 .txt 文件。例如,我的测试文件是:“NNEEENNW NSWENNNS”
此 function 读取数据文件并将数据转换为拆分每个字符的列表列表。
def read_file(file_name):
with open(file_name, "r") as f:
lines = [list(str(line.rstrip().upper())) for line in f]
return lines
所以对于我上面的文件,它给了我
[['N', 'N', 'E', 'E', 'E', 'N', 'N', 'W'], ['N', 'S', 'W', 'E', 'N', 'N', 'N','S']]
在笛卡尔 map 中,在 (y, x) 从 (0, 0) 开始,每次向 N 和 E 移动都会加 1,向 W 和 S 每次移动都会减去 1。
我有这个 function,它给了我最终的坐标:
def convert_coodinates(coordinates):
s = Counter({'N': 0, "S":0, "W": 0, 'E':0})
for i in coordinates:
s.update(i)
final_latitude = s['N'] - s["S"]
final_longitude = s['E'] - s["W"]
final = (final_longitude, final_latitude)
print(final)
所以上面的例子会给我:
(2, 6)
理想情况下我会打印
(2, 4)
(2, 6)
基本上它应该打印第一组坐标,然后是第一组+第二组......依此类推,直到最后一行将成为最终目的地。
有任何想法吗?
问题是您一次更新循环中的Counter
,然后计算纬度和经度。
这导致s
仅包含将所有列表元素累积在一起后的值。
倾倒s
将确认它具有相同的值Counter({'N': 8, 'E': 4, 'S': 2, 'W': 2})
。
您基本上需要的是计算每次迭代中的值:
from collections import Counter
def convert_coodinates(coordinates):
s = Counter({'N': 0, "S":0, "W": 0, 'E':0})
for idx, i in enumerate(coordinates):
s.update(i)
final_latitude = s['N'] - s["S"]
final_longitude = s['E'] - s["W"]
final = (final_longitude, final_latitude)
print(final)
coord = [['N', 'N', 'E', 'E', 'E', 'N', 'N', 'W'], ['N', 'S', 'W', 'E', 'N', 'N', 'N','S']]
convert_coodinates(coord)
Output:
(2, 4)
(2, 6)
Emmm,简单的方法是将计算和print
代码放入for 循环中:
def convert_coodinates(coordinates):
s = Counter({'N': 0, "S":0, "W": 0, 'E':0})
longitude,latitude = 0,0
for i in coordinates:
s.update(i)
longitude = s['E'] - s["W"]
latitude = s['N'] - s["S"]
final = (longitude, latitude)
print(final)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.