gpt4 book ai didi

python - 如何导入列表? ( python )

转载 作者:行者123 更新时间:2023-12-01 05:21:48 25 4
gpt4 key购买 nike

我是Python的新手。(我正在研究一周左右)
我正在尝试将文件导入为列表,然后从中选择一个随机词以在循环中使用它。我不太确定该怎么做!提前致谢

最佳答案

这是广义形式的答案:

f = open("path/to/file", "r") # opens the file as read-only
content = f.read() # there are easier ways to do this, but....
### do whatever you're doing here....
f.close() # MAKE SURE YOU CLOSE FILES when you're done with them
# if you don't, you're asking for memory leaks.


您也可以使用上下文管理器,但阅读起来有些困难:

with open("path/to/file","r") as f:
content = f.read() # again, this is not the BEST way....
### do stuff with your file
# it closes automatically, no need to call f.close()


在文件操作之外,这是字符串->列表内容:

"a,b,c,d,e,f,g".split(',')
-> ['a','b','c','d','e','f','g']
# str.split creates a list from a string, splitting elements on
# whatever character you pass it.


这是 random.choice

import random

random.choice(['a','b','c','d','e','f','g'])
-> 'c' # chosen by fair dice roll, guaranteed to be random! ;)
# random.choice returns a random element from the list you pass it

关于python - 如何导入列表? ( python ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com