def loadfunc(filestr):
listoftuples = []
listofnumbers = []
tupleinlist = []
with open(filestr, 'r') as file:
for line in file:
for item in line:
if item.isdigit():
listofnumbers.append(float(item))
else:
word = item
tupleinlist.append(word)
tupleinlist.append(listofnumbers)
listoftuples.append(tuple(tupleinlist))
return listoftuples
print(listoftuples)
上面是我的代码。因此,要求是将数据从 .csv 文件加载到元组列表中。文件中的数据类似于:
- apple 23.2 24.3 25.6
- banana 22.1 20.0 19.9
列表中的每个元组都必须是(word, listoffloats)
,因此列表如下所示:
[(apple, [23.2, 24.3, 25.6]), (banana, [22.1, 20.0, 219.9])]
但是在我的代码中,它搞砸了并且不返回它,因为当它迭代每个“行”中的“item”时,它会迭代每个字符(例如 .
、 a
、p
、p
、l
、e
),而不是像 这样的 item >苹果
、23.2
等
请帮忙,我不知道如何解决这个问题,并且本教程不允许使用 csv 库/模块。
最佳答案
假设您有 t.csv 中的数据。您可以将数据保存在 results
列表中,然后在文件中的每一行上使用 split
并将拆分结果附加到 results
中。使用 csv 模块可以为您完成此操作,但您可以使用 split
复制分隔符行为。
with open('t.csv', 'r') as f:
results = []
for line in f:
words = line.split(',')
results.append((words[0], words[1:]))
print results
关于python - 如何从 .csv 文件加载数据而不导入 .csv 模块/库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32327936/