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])]
但我的代码是螺丝这并不会因为当它遍历每个“行”,“项”归来吧,它遍历每个字符(如.,a,p,p,l,e),而不是项目是一样的东西apple,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
| 归档时间: | 
 | 
| 查看次数: | 17157 次 | 
| 最近记录: |