好的,我走了!我顺便说一句,我是一个菜鸟,我正努力学习。 我不得不写一些代码来打开一个csv文件并格式化列表,这样它可以与Libsvm一起使用但是无论如何 这是我到目前为止写的代码:
import csv
with open ('testingSeta.csv')as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
for i in reader:
i.insert (0, i.pop(13))
print (" ".join(i))
这给了我一个这样的列表:
-1 0 1 1 0 1 1 1 4 5 6 5 5 8
-1 0 1 0 0 1 1 1 4 3 7 1 3 6
1 3 7 2 0 4 4 1 41 46 86 20 18 48
1 10 11 0 0 6 6 3 26 65 102 25 16 38
testingSeta.csv原始格式:
0,1,1,0,1,1,1,4,5,6,5,5,8,-1
0,1,0,0,1,1,1,4,3,7,1,3,6,-1
3,7,2,0,4,4,1,41,46,86,20,18,48,1
10,11,0,0,6,6,3,26,65,102,25,16,38,1
我希望这样的名单是这样订购的:
-1 1:0 2:1 3:1 4:0 5:1 6:1 7:1 8:4 9:5 10:6 11:5 12:5 13:8
-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:4 9:3 10:7 11:1 12:3 13:6
1 1:3 2:7 3:2 4:0 5:4 6:4 7:1 8:41 9:46 10:86 11:20 12:18 13:48
1 1:10 2:11 3:0 4:0 5:6 6:6 7:3 8:26 9:65 10:102 11:25 12:16 13:38
编号' 1:'应始终从第二个数字/值开始。 任何身体都能帮忙吗? 谢谢你的时间
答案 0 :(得分:1)
尝试这样:
>>> with open('your_file') as f:
... for x in f:
... line = x.strip().split(',')
... print "{} ".format(line[-1]) + " ".join("{}:{}".format(i,y) for i,y in enumerate(line[:-1],start=1))
...
-1 1:0 2:1 3:1 4:0 5:1 6:1 7:1 8:4 9:5 10:6 11:5 12:5 13:8
-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:4 9:3 10:7 11:1 12:3 13:6
1 1:3 2:7 3:2 4:0 5:4 6:4 7:1 8:41 9:46 10:86 11:20 12:18 13:48
1 1:10 2:11 3:0 4:0 5:6 6:6 7:3 8:26 9:65 10:102 11:25 12:16 13:38
答案 1 :(得分:1)
>>> with open ('testingSeta.csv') as csvfile:
... reader = csv.reader(csvfile, delimiter = ',')
... for i in reader:
... last = i.pop(13)
... for index,string in enumerate( i ) :
... i[ index ] = str(index+1) + ":" + string
... print last + " " + " ".join(i)
...
-1 1:0 2:1 3:1 4:0 5:1 6:1 7:1 8:4 9:5 10:6 11:5 12:5 13:8
-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:4 9:3 10:7 11:1 12:3 13:6
1 1:3 2:7 3:2 4:0 5:4 6:4 7:1 8:41 9:46 10:86 11:20 12:18 13:48
1 1:10 2:11 3:0 4:0 5:6 6:6 7:3 8:26 9:65 10:102 11:25 12:16 13:38
答案 2 :(得分:1)
with open('testingSeta.csv') as f:
for line in csv.reader(f):
print(' '.join(
[line[-1]] +
['{0}:{1}'.format(*x) for x in enumerate(line[:-1], start=1)]))
-1 1:0 2:1 3:1 4:0 5:1 6:1 7:1 8:4 9:5 10:6 11:5 12:5 13:8
-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:4 9:3 10:7 11:1 12:3 13:6
1 1:3 2:7 3:2 4:0 5:4 6:4 7:1 8:41 9:46 10:86 11:20 12:18 13:48
1 1:10 2:11 3:0 4:0 5:6 6:6 7:3 8:26 9:65 10:102 11:25 12:16 13:38