我正在制作的剧本:
def plotRegression(data):
'''read labdata.txt and plot
x,y coordinates using formula'''
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.speed()
#set up variables
x_list = [i[0] for i in data]
y_list = [i[1] for i in data]
#formula goes here
#set window size here
with open("labdata.txt") as f:
#coords = [map(int, line.split()) for line in f]
coords = list(map(int, line.split()) for line in f)
plotRegression(coords)
labdata.txt示例:
44 71
79 37
78 24
运行脚本时出错:
Traceback (most recent call last):
File "plot_regression.py", line 23, in <module>
plotRegression(coords)
File "plot_regression.py", line 12, in plotRegression
x_list = [i[0] for i in data]
File "plot_regression.py", line 12, in <listcomp>
x_list = [i[0] for i in data]
TypeError: 'map' object is not subscriptable
我从这个问题的目标是从labdata.txt读取数据并准备好数据作为函数读取的整数。我想我现在已经过于复杂化,但我有一些东西要学习,所以感谢你的帮助!
在with语句中我注释掉了一行。我第一次在别人的代码中看到了这个map方法,我想给它一个看似有用的镜头。但是,经过一些错误和研究后,它看起来像是Python 2代码而我使用的是Python 3,因此存在一些差异,这些差异无法让我正确运行代码。
这里在stackoverflow上的搜索解释了map函数“返回一个生成器”,但我不确定这意味着什么。有人可以向我解释为什么我的尝试不起作用吗?
答案 0 :(得分:0)
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> map(int, '1 2 3 4'.split())
<map object at 0x7f9202ae9518>
>>> m = map(int, '1 2 3 4'.split())
>>> m[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'map' object is not subscriptable
>>> list(map(int, '1 2 3 4'.split()))
[1, 2, 3, 4]
>>> list(map(int, line.split()) for line in '1 2\n3 4'.split('\n'))
[<map object at 0x7f9202ae9780>, <map object at 0x7f9202ae9828>]
>>> list(list(map(int, line.split())) for line in '1 2\n3 4'.split('\n'))
[[1, 2], [3, 4]]
>>> [[int(num) for num in line.split()] for line in '1 2\n3 4'.split('\n')]
[[1, 2], [3, 4]]