我有一个问题
说,我在包含这些值的csv文件中有几列和一列:
0 1 2 1 1 2 3 2 66 2 0 1 2 66
我有一个新创建的log csv文件。
我的目标是将列中值66之前的3个值复制到新创建的csv文件中。 我尝试了很多不同的东西。 我尝试的最后一件事是“枚举”选项,但此选项也不考虑前面的3个值
我的代码是
导入csv 导入系统 导入日期时间
def log_write_line(* args):
# Make the global log_file variable accessible from this function using the 'global' keyword
global log_file
# Convert the parameters into a list of parameters
#args = ['my_block_nr', 'my_trial_nr',1]
args = list(args)
# Need to make sure that every single items in the 'args' list is of the variable type 'string'
# In order for the generic 'join' method below to work. It accepts strings, not integers.
# therefore 'list comprehensions' is necessary.
# Read the line below as: 'args' becomes a list of every item 'a' converted to a string
args = [str(a) for a in args]
# Join those parameters together to a single comma-separated line.
# At the end of these joined values, add a new line ("\n") character to move to the next line
# in my log file.
log_line = ','.join(args) + "\n"
print 'log line:', log_line
# Actually write the composed log line to the log file
log_file.write(log_line)
# Flush the data written to the file directly to the disk
log_file.flush()
def log_write_value(value):
# Make the global log_file variable accessible from this function using the 'global' keyword
global log_file
print 'log write value:', value, type(value)
log_file.write(str(value))
log_file.write(',')
log_file.flush()
def log_write_newline(): #使用'global'关键字
从此函数访问全局log_file变量global log_file
log_file.write('\n')
log_file.flush()
global log_file
filename = datetime.datetime.now()。strftime(“experiment-%y%m%d_%H%M%S.csv”) log_file = open(filename,'w +')
def open_data_thought_probes_plus_new_file():
f = open('DATA_File.csv','rU')
csv_f = csv.reader(f)
for row in csv_f:
ints = [row[0]]
list(enumerate(ints, start = (-3)))
print list
log_write_value(list(enumerate(ints, start = 3)))
我非常感谢任何帮助。对我来说最大的问题是,是否有一个代码在考虑固定值之前采用前面的3个值?或者你最好这样做?
非常感谢!! 台伯
答案 0 :(得分:0)
如果我理解了这个问题,我认为你与enumerate
很接近。如果您有一个列表l
:
l = [0, 1, 2, 1, 1, 2, 3, 2, 66, 2, 0, 1, 2, 66]
for i,x in enumerate(l):
if x == 66:
print l[i-3:i] # access the list via indices, i
#copy these values to log
>>>[2, 3, 2]
>>>[0, 1, 2]
或者使用列表理解,将返回列表列表:
[l[i-3:i] for i,x in enumerate(l) if x == 66]
>>>[[2, 3, 2], [0, 1, 2]]
不幸的是,如果66
是前3个元素之一,两个方法都会返回一个空列表:
l = [0, 1, 66, 2, 1, 2, 3, 2, 66, 2, 0, 1, 2, 66]
for i,x in enumerate(l):
if x == 66:
print l[i-3:i]
>>[]
>>[2, 3, 2]
>>[0, 1, 2]