通过列表在CSV文件中创建新列 [英] creating a new column in a CSV file from a list
问题描述
我一直试图弄清楚如何获取列表并使用它在csv文件中创建新列.我的想法是,我有一个cvs文件,我已将每一行的最后一项用于创建列表,将其混洗,然后将其添加到文件末尾.
I have been trying to figure out how to take a list and use it to create a new column in my csv file. The idea is that I have a cvs file, I've taken the last item of each row to create a list, shuffled it and then I need to add it to the end of the file.
我遇到了一些但已解决的思考"问题: Python不会附加字符串列表,因此我将其转换为int. 删除列标题并将其重新添加.
Some issues I ran into but 'think' I have fixed are: Python won't append a list of strings so I converted to int. Removing the column header and adding it back in.
到目前为止,我有:
def fun():
import csv
import random
f = open('CSVFUN.csv')
csv_f = csv.reader(f)
ISI = []
for line in csv_f:
ISI.append(line[4])
ISI = ISI[1:]
random.shuffle(ISI)
delay = [int(i) for i in ISI]
print(delay)
with open('CSVFUN.csv','r') as csvinput:
with open('CSVOUTPUT.csv','w') as csvoutput:
writer = csv.writer(csvoutput, lineterminator='\n')
reader = csv.reader(csvinput)
for row in reader:
if row[0] == 'practicesentence':
writer.writerow(row+['FINALaudioDelay'])
else:
for i in delay:
writer.writerow(row+[delay[i]])
我认为我现在遇到的问题是,我的最终else语句正在遍历延迟列表并将该列表的每个元素添加到一行中的每个元素.因此,第1项有8个延迟,第2项有8个延迟,依此类推.
I think the issue I am having now is that my final else statement is iterating through my list of delay and adding each element of the list to each element in a row. So item 1 is getting 8 delays, item 2 gets 8 delays, and so on.
我想要的是第1个项目具有第一个延迟,第二个项目具有第二个延迟,依此类推.
What I want is for item 1 to go with the first delay, item 2 with the second delay and so on.
我感觉自己犯了一些愚蠢的错误,但我只是不知道这是什么....
I feel like I'm making some sort of stupid mistake but I just can't figure out what it is....
推荐答案
如果要访问delay
的第i个元素,则您的代码正确.但是,由于您说for i in delay
,所以i
已经是delay
的元素.尝试将最后一行中的delay[i]
换成delay[i]
.下面是一个例子
If you want to access the ith element of delay
, then your code is correct. However, since you say for i in delay
, i
is already an element of delay
. Try changing out delay[i]
for just i
in the last line. An example is below
list = [5, 4]
for i in list:
print i
这将返回:
5
4
但是,如果您这样做:
list = [5, 4]
for i in list:
print list[i]
这将不起作用,因为list
仅包含索引为0和1的元素,而不是索引为4和5的元素.
This won't work because list
only has elements with indices 0 and 1, not 4 and 5.
这篇关于通过列表在CSV文件中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!