【发布时间】:2014-01-31 17:53:37
【问题描述】:
所以现在我有这个(在 Python 2.7 中):
if y == ports[0]:
Array1.append(x)
elif y == ports[1]:
Array2.append(x)
elif y == ports[2]:
Array3.append(x)
elif y == ports[3]:
Array4.append(x)
else:
Array5.append(x)
for x in Array1:
target=open('Array1.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array1.csv\n"
for x in Array2:
target=open('Array2.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array2.csv\n"
for x in Array3:
target=open('Array3.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array3.csv\n"
for x in Array4:
target=open('Array4.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array4.csv\n"
for x in Array5:
target=open('Array5.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array5.csv\n"
如果我这样做,程序会更快完成吗:
if y == ports[0]:
Array1.append(x)
target=open('Array1.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array1.csv\n"
elif y == ports[1]:
Array2.append(x)
target=open('Array2.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array2.csv\n"
elif y == ports[2]:
Array3.append(x)
target=open('Array3.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array3.csv\n"
elif y == ports[3]:
Array4.append(x)
target=open('Array4.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array4.csv\n"
else:
Array5.append(x)
target=open('Array5.csv', 'a')
target.write(x + ",\n")
target.close()
print "Added IP address " + x + " to Array5.csv\n"
或者我会发现有什么不同吗?或者也许有第三种更快的方法?将项目写入列表时是否重要?
【问题讨论】:
-
你为什么不直接测量一下?
-
无论哪种情况,我都有一个建议。不是有五个变量
Array1到Array5,而是有一个列表Arrays,其中包含五个数组。那么您的第一个代码可能是for i in range(5): for x in Array[i]:,而不是连续五个循环。