我有2个列表生成了file1& file2(其中所有字母都是随机值编号)。
每个文件中的行是同一对象的值。
例如,对象1具有以下值,所有来自第1行的所有2个文件
object1:
a, b, c, d, e, f
g, h, i, j, k, l
$ cat file1
a, b, c, d, e, f # line1 - object1
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
$ cat file2
g, h, i, j, k, l # line1 - object1
g, h, i, j, k, l
g, h, i, j, k, l
g, h, i, j, k, l
g, h, i, j, k, l
g, h, i, j, k, l
现在我有一个脚本有一些列表,需要在循环中获得来自这两个文件的值
daytime = now.strftime("%A")
varlist1 = [a, b, c, d, e, f]
varlist2 = [g, h, i, j, k, l]
static1 = [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
for li1,li2,st1 in zip(varlist1, varlist2, static1)
if (li1 != 0 and li2 == 0 and daytime == st1):
print "Go"
else:
print "NoGo"
我需要逐行读取文件并从列表varlist1,varlist2中的文件传递变量,然后处理循环中文件的每一行
实现这一目标的最佳方法是什么。我无法找到快速实现目标的方法吗?
非常感谢
答案 0 :(得分:3)
我需要逐行读取文件并从列表varlist1,varlist2中的文件传递变量,然后处理循环中文件的每一行
我不完全确定你要在这里完成什么,但我可以给你一个应该可以轻松调整以满足你需要的演示。我还假设a
,b
,...应该是此演示的整数。您可以像这样逐行处理文件:
f1 = open('file1', 'r')
f2 = open('file2', 'r')
for i in range(3): # your actual conditions go here
# read in next line from each of the files and store them in a list of ints
varlist1 = f1.readline().strip().split(', ')
varlist1 = [int(x) for x in varlist1] # use float(x) here if a,b,... are floats
varlist2 = f2.readline().strip().split(', ')
varlist2 = [int(x) for x in varlist2] # use float(x) here if g,h,... are floats
# do something more interesting with varlist1, varlist2 here
# than just printing them
print(varlist1)
print(varlist2)
f1.close()
f2.close()
然而,而不是逐行处理文件,我会像这样准备所有的变量列表:
with open('file1', 'r') as f1:
data1 = f1.read().splitlines()
with open('file2', 'r') as f2:
data2 = f2.read().splitlines()
varlists1 = [[int(x) for x in y.split(', ')] for y in data1] # or float(x) ...
varlists2 = [[int(x) for x in y.split(', ')] for y in data2]
现在您可以执行以下操作:
for varlist1, varlist2 in zip(varlists1, varlists2):
for li1,li2,st1 in zip(varlist1, varlist2, static1):
# your code here