【问题标题】:Faster to add all items to an array then write the array to file, or faster to write the item to a file and then add to array one at a time?更快地将所有项目添加到数组然后将数组写入文件,还是更快地将项目写入文件然后一次添加到数组?
【发布时间】: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"

或者我会发现有什么不同吗?或者也许有第三种更快的方法?将项目写入列表时是否重要?

【问题讨论】:

  • 你为什么不直接测量一下?
  • 无论哪种情况,我都有一个建议。不是有五个变量Array1Array5,而是有一个列表Arrays,其中包含五个数组。那么您的第一个代码可能是for i in range(5): for x in Array[i]:,而不是连续五个循环。

标签: python arrays file


【解决方案1】:

这可能无关紧要。更重要的是不要不断地重新打开文件:

with open('Array1.csv', 'a') as target:
    for x in Array1:
        target.write(x + ",\n")
        print "Added IP address " + x + " to Array1.csv\n"

另外,我不知道它是否适用于此,但the csv module 确实存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多