Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
所以我正在导入一个 txt 说
abc dfg fgh
包含在 txt 文件中。虽然目前我得到它的形式
[[abc],[dgf],[fgh],]
当我试图得到
[['a','b','c'],['d','g','f'],['f','g','h']]
我目前的代码是
f = open(filename, 'rU') result = [line.list(',') for line in f.readlines()]
我怎样才能改变它来分隔列表中的每个字符?
使用 just list(line.rstrip()),list()可以将字符串转换为单个字符的列表:
list(line.rstrip())
list()
with open('filname') as f: result = [list(line.rstrip()) for line in f]
并且不要使用file.readlines,您可以遍历文件对象本身。
file.readlines
演示:
>>> list("foobar") ['f', 'o', 'o', 'b', 'a', 'r']