[英]How to save a list and access values in a list in Python— .txt file
I want to create a module that checks whether a number is prime or not, and to list all of the primes before it. 我想创建一个模块来检查数字是否为素数,并列出所有素数。
The functions in the module would take a bit of time if it had to generate the list of primes every single time it was created. 如果必须在每次创建素数时生成素数列表,模块中的函数将花费一些时间。
How do I open a .txt file that is in the same folder as the program is in, then have it access the data from it and create a list based off of that? 如何打开与程序所在文件夹相同的.txt文件,然后让它从中访问数据并根据该文件创建列表? The .txt file will be saved a list afterwards when the function is completed. 该函数完成后,.txt文件将保存在列表中。 I also need a bit of guidance on how to actually save the file in a given location. 我还需要一些关于如何在给定位置实际保存文件的指导。
Any suggestions or tips would be great. 任何建议或提示都会很棒。 Thanks! 谢谢!
I would pickle a set
object, you could do this: 我会挑选一个set
对象,你可以这样做:
import cPickle as pickle
primes_set = set([2,3,5])
pickle.dump(primes_set, open('primes_set.pkl', 'wb'))
my_primes = pickle.load(open('primes_set.pkl', 'rb')) # to load the object
After you created a pickle file, you could use it like this: 创建pickle文件后,您可以像这样使用它:
def get_primes(my_nums):
'''
Return only prime numbers from inputted list.
'''
my_primes = pickle.load(open('primes_set.pkl', 'rb'))
return [num for num in my_nums if num in my_primes]
Have a look at io in python http://docs.python.org/2/tutorial/inputoutput.html 在python中查看io http://docs.python.org/2/tutorial/inputoutput.html
as you seem to be doing number crunching i would use pytables (hdf5 binary file) to save load and update arrays 因为你似乎在做数字运算,我会使用pytables(hdf5二进制文件)来保存负载和更新数组
You have several options. 你有几个选择。 If you want to save the list as a list, the Pickle is probably the best way to go. 如果您想将列表保存为列表,那么Pickle可能是最好的方法。
If you don't mind processing your txt file then you could just store it as a csv , which python will turn back into a list readily. 如果您不介意处理您的txt文件,那么您可以将其存储为csv ,python将很容易地转回列表。
In order to open a file, just use 要打开文件,只需使用
filereader = open("example.txt")
then the variable filereader will contain the file's data. 那么变量filereader将包含文件的数据。
allprimes = []
for line in filereader:
allprimes.append(int(line)) #assuming one number is stored per line
allprimes will now contain all numbers stored in the file. allprimes现在将包含存储在文件中的所有数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.