本质上,我想从文件中提取一行文本,将字符分配给一个列表,然后创建一个列表中所有单独字符的列表——一个列表列表。
目前,我已经尝试过:
fO = open(filename, 'rU')
fL = fO.readlines()
这就是我所拥有的。我不太清楚如何提取单个字符并将它们分配给一个新列表。
我从文件中得到的行将类似于:
fL = 'FHFF HHXH XXXX HFHX'
我想把它变成这个列表,每个单独的字符:
['F', 'H', 'F', 'F', 'H', ...]
我好像有点晚了,但是...
a='hello'
print list(a)
# ['h','e','l','l', 'o']
字符串是可迭代的(就像列表一样)。
我在解释你真的想要这样的东西:
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 将包含文件中的所有字符。
3.5 版以后允许使用PEP 448 - Extended Unpacking Generalizations:
>>> string = 'hello'
>>> [*string]
['h', 'e', 'l', 'l', 'o']
这是语言语法的规范,因此它比调用更快list:
>>> from timeit import timeit
>>> timeit("list('hello')")
0.3042821969866054
>>> timeit("[*'hello']")
0.1582647830073256
因此,要将字符串hello作为单个字符添加到列表中,请尝试以下操作:
newlist = []
newlist[:0] = 'hello'
print (newlist)
['h','e','l','l','o']
但是,这样做更容易:
splitlist = list(newlist)
print (splitlist)
fO = open(filename, 'rU')
lst = list(fO.read())
或者在处理非常非常大的文件/列表时使用一个花哨的列表理解,它应该是“计算效率更高”
fd = open(filename,'r')
chars = [c for line in fd for c in line if c is not " "]
fd.close()
顺便说一句:被接受的答案不考虑空格......
a='hello world'
map(lambda x:x, a)
['你好世界']
一种简单的方法是使用函数“map()”。
在 python 中,很多东西都是可迭代的,包括文件和字符串。遍历文件处理程序会为您提供该文件中所有行的列表。遍历一个字符串会为您提供该字符串中所有字符的列表。
charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes
for line in open(filePath):
for char in line:
charsFromFile.append(char)
#apply code on each character here
或者如果你想要一个班轮
#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]
.
.
编辑:正如 agf 提到的,您可以使用itertools.chain.from_iterable
他的方法更好,除非您想要指定要抓取哪些线的能力
list(itertools.chain.from_iterable(open(filename, 'rU)))
然而,这确实需要一个人熟悉 itertools,因此失去了一些可读性
如果您只想遍历字符,而不关心存储列表,那么我会使用嵌套的 for 循环。这种方法也是最易读的。
因为字符串是(不可变的)序列,它们可以像列表一样解包:
with open(filename, 'rU') as fd:
multiLine = fd.read()
*lst, = multiLine
运行 map(lambda x: x, multiLine) 时,这显然更高效,但实际上它返回的是地图对象而不是列表。
with open(filename, 'rU') as fd:
multiLine = fd.read()
list(map(lambda x: x, multiLine))
将地图对象转为列表将比解包方法花费更长的时间。