lov*_*ate 11 python split list turtle-graphics
我正在尝试读取文件并用逗号分割每行中的单元格,然后仅显示包含纬度和经度信息的第一个和第二个单元格.这是文件:
时间,纬度,经度,类型2015-03-20T10:20:35.890Z,38.8221664,-122.7649994,地震2015-03-20T10:18:13.070Z,33.2073333,-116.6891667,地震2015-03-20T10:15:09.000Z,62.242 ,-150.8769,地震
我的节目:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = readfile.readlines()
Type = readlines.split(",")
x = Type[1]
y = Type[2]
for points in Type:
print(x,y)
getQuakeData()
Run Code Online (Sandbox Code Playgroud)
当我尝试执行此程序时,它给了我一个错误
"AttributeError:'list'对象没有属性'split'
请帮我!
aba*_*ert 16
我认为你实际上在这里有更广泛的困惑.
最初的错误是你试图调用split整个行列表,而不是split字符串列表,只能是字符串.所以,你需要split 每一行,而不是整个行.
然后你正在做for points in Type,并期望每个points人都给你一个新的x和y.但这不会发生.Types只是两个值,x并且y,所以首先points会x,然后点会y,然后你会做.因此,再次,您需要遍历每一行并从每一行获取x和y值,而不是从一行循环到Types单个行.
因此,所有内容都必须遍历文件中每一行的循环,并为每行执行splitinto x和yonce.像这样:
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()
Run Code Online (Sandbox Code Playgroud)
作为旁注,你真的应该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()
Run Code Online (Sandbox Code Playgroud)
或者,更好的写作方式可能是:
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()
Run Code Online (Sandbox Code Playgroud)
最后,您可能需要查看NumPy和Pandas,这些库确实为您提供了一种方法,可以在整个数组或数据框架上隐式映射功能,几乎与您尝试的方式相同.