对于我的项目,我做了一些事情并从命令行输出中提取特定行,然后将其插入列表中。从那里,我将列表导出到训练文件中,以供稍后使用的学习算法。问题是当我从命令行中提取信息时,它会提取
"Number\n"
当我将列表附加到文本文件时,它不会打印
Number, Number, Number
相反,它正在打印
Number
Number
Number
它正在应用换行符,这对我来说几乎没用。通过谷歌搜索,我发现了这个链接 Strip all the elements of a string list 解释我的想法正是我解决问题所需要的。它去掉换行符并将列表变成我以后需要使用的内容。除非出于某种原因它不起作用。
这是我的代码
def exportlist(self):
file = open('Trainingfile.txt','a+')
# i pass it into a variable since i ran into some odd errors if i try
# to apply the map function to self.vectorlist
my_list= self.vectorlist
print(my_list) # prints [ 'number\n', 'number\n'......]
# WHAT THE ABOVE LINK AND OTHERS SAID SHOULD WORK
strip_list= map(str.rstrip('\n'), my_list)
print(strip_list) # prints "map object at 0x00000002C...."
self.vectorlist = strip_list # test code
print(self.vectorlist) # prints same as strip_list
file.close()
如果我使用 chr.split 而不是 strip,我会得到类似的结果。 打印 my_list 会打印格式不正确的列表。 打印 strip_list 应该是格式正确的列表,打印我认为是内存位置“0x0000000002C....”我在网上找到的所有内容都告诉我它不应该打印这个。它应该打印格式正确的列表。有谁知道为什么会发生这种情况?每次我使用 map 功能时都会发生这种情况。我尝试了多种方法从列表中删除“\n”,但它总是返回相同的内容。
最佳答案
您需要将结果转换为列表:
strip_list = list(map(str.rstrip('\n'), my_list))
在 Python 3 中 map()
返回一个 map 对象。这是一个迭代器。您可以使用 list()
将其转换为列表。
关于python - 字符串列表打印内存位置的映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34084127/