将字符串分解为Python中的字符列表 [英] Break string into list of characters in Python
问题描述
基本上,我想从文件中吸收一行文本,将字符分配给列表,并创建列表中所有单独字符的列表-列表列表.
Essentially I want to suck a line of text from a file, assign the characters to a list, and create a list of all the separate characters in a list -- a list of lists.
此刻,我已经尝试过:
fO = open(filename, 'rU')
fL = fO.readlines()
这就是我所拥有的.我不太了解如何提取单个字符并将其分配到新列表中.
That's all I've got. I don't quite know how to extract the single characters and assign them to a new list.
我从文件中得到的行将类似于:
The line I get from the file will be something like:
fL = 'FHFF HHXH XXXX HFHX'
我想把它变成这个列表,每个单独的字符都单独出现:
I want to turn it into this list, with each single character on its own:
['F', 'H', 'F', 'F', 'H', ...]
推荐答案
字符串是可迭代的(就像列表一样).
Strings are iterable (just like a list).
我是在解释您确实想要像这样的东西:
I'm interpreting that you really want something like:
fd = open(filename,'rU')
chars = []
for line in fd:
for c in line:
chars.append(c)
或
fd = open(filename, 'rU')
chars = []
for line in fd:
chars.extend(line)
或
chars = []
with open(filename, 'rU') as fd:
map(chars.extend, fd)
字符将包含文件中的所有字符.
chars would contain all of the characters in the file.
这篇关于将字符串分解为Python中的字符列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!