我认为您实际上在这里更加困惑。
最初的错误是您试图调用split
整个行列表,而不能split
列出一个字符串列表,而只能是一个字符串。因此,您需要split
每一行 ,而不是全部。
然后您正在做for points in Type
,并期望每一个points
都能给您带来新的x
感觉y
。但这不会发生。Types
是两个值,x
和y
,所以首先points
是x
,然后点是y
,然后就可以完成。因此,同样,您需要遍历每行并从每行 获取x
和y
值,而不是遍历单行中的一行。 __Types
因此,所有内容都必须循环进入文件中的每一行,并对每一行执行一次split
intox
和y
一次。像这样:
def getquakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
for line in readfile:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
getquakeData()
附带说明一下,您确实应该close
在文件中添加一个理想的with
语句,但是我将在最后讨论。
有趣的是,这里的问题并不在于您是个新手,而是您试图以专家会用的抽象方式来解决问题,而现在还不了解细节。这是完全可行的。您只需要明确地映射功能,而不是隐式地进行功能映射。像这样:
def getquakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = readfile.readlines()
Types = [line.split(",") for line in readlines]
xs = [Type[1] for Type in Types]
ys = [Type[2] for Type in Types]
for x, y in zip(xs, ys):
print(x,y)
getquakeData()
或者,一种更好的书写方式可能是:
def getquakeData():
filename = input("Please enter the quake file: ")
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
# no need for readlines; the file is already an iterable of lines
# also, using generator expressions means no extra copies
types = (line.split(",") for line in readfile)
# iterate tuples, instead of two separate iterables, so no need for zip
xys = ((type[1], type[2]) for type in types)
for x, y in xys:
print(x,y)
getquakeData()
最后,您可能想看一下NumPy和Pandas,它们 确实 为您提供了一种以几乎与您尝试的方式相同的方式在整个数据数组或数据帧上隐式映射功能的方法。