属性错误:“list”对象没有属性“split”
- 2025-04-10 09:47:00
- admin 原创
- 44
问题描述:
我正在尝试读取一个文件,并用逗号将每行中的一个单元格拆分,然后仅显示包含有关纬度和经度信息的第一个和第二个单元格。这是文件:
time,latitude,longitude,type
2015-03-20T10:20:35.890Z,38.8221664,-122.7649994,earthquake
2015-03-20T10:18:13.070Z,33.2073333,-116.6891667,earthquake
2015-03-20T10:15:09.000Z,62.242,-150.8769,earthquake
我的程序:
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()
当我尝试执行该程序时,出现错误
AttributeError: 'list' object has no attribute 'split'
请帮我!
解决方案 1:
我认为你实际上在这里感到更加困惑。
最初的错误是你试图调用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,这些库确实为您提供了一种几乎以与您尝试的方式相同的方式将功能隐式映射到整个数组或数据帧上的方法。
解决方案 2:
问题是readlines
是一个字符串列表,每个字符串都是一行filename
。也许你的意思是:
for line in readlines:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
解决方案 3:
我所做的是通过将 readlines 转换为字符串来快速修复,但我没有重新开始它,但它有效,我不知道是否有限制
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = str(readfile.readlines())
Type = readlines.split(",")
x = Type[1]
y = Type[2]
for points in Type:
print(x,y)
getQuakeData()
解决方案 4:
如果您因为收到此(或类似)错误而到达此处:AttributeError: 'list' object has no attribute ...
,则表示您尝试调用列表对象上未定义的方法。1出现此错误的一个非常常见的原因是您无意中处理了列表对象,而该对象未定义您尝试调用的方法。请务必事先检查类型。
一些常见的例子(未指定 dtype 的 numpy 数组、API 调用的输出、(意外的)Python 对象列表等):
# arr is an array of Python lists without a specific numeric dtype
arr = np.array([[1,2,3], [4,5]], dtype=object)
arr[0].mean() # AttributeError
# j is a list of dicts, so cannot call a dict method
j = [{'key1': 'val1', 'key2': 'val2'}]
j.get('key1') # AttributeError
在许多情况下,您可以简单地打印数据类型,例如print(type(my_data))
会显示意外的输入类型。此外,也许可以使用 try-except 块来捕获意外的数据类型。
话虽如此,对于 OP 的实际问题,数据似乎是一个 csv 文件,因此使用标准csv
模块或pandas
看起来都是更干净的选择。
import csv
with open(filename, 'r') as file:
for line in csv.reader(file):
x, y = line[1], line[2]
print(x, y)
即使第一行看起来像是文件的标题,我们甚至可以使用csv.DictReader
:
with open(filename, 'r') as file:
for line in csv.DictReader(file):
x, y = line['latitude'], line['longitude']
print(x, y)
使用 pandas,这是一个单一函数调用。
# pip install pandas
import pandas as pd
df = pd.read_csv(filename)
1不算 dunder 方法,Python 列表定义、、、、、、、、、和方法append
(您可以使用进行验证);不在其中。clear
`copycount
extendindex
insertpop
removereverse
sortdir([])
split`
扫码咨询,免费领取项目管理大礼包!