python - List of words within List as character
问题描述
I have a file having data in form
Your
Name
I am reading the file and want to convert the data in the list but each word as a separate list in the form of words. I tried the below code
def return_list():
a1_filename = tkinter.filedialog.askopenfilename()
a1_file = open(a1_filename, 'r')
grade= []
line = a1_file.readline()
while (line != ''):
for words in line:
b = words.rstrip('\n')
grade.append([b])
line = a1_file.readline()
return grade
My output is:
[['Y'], ['o'], ['u'], ['r'], [''], ['N'], ['a'], ['m'], ['e'], ['']]
But what I am trying to get is
[['Y','o','u','r'], ['N','a','m','e']]
解决方案
You have two problems. The main one is that you're trying to build a two-level data structure with a single-feature construction. Instead, build the list of letters you want, and then append that list to your master list.
The second problem is that you're using append
on a list, which adds the entire list structure.
while (line != ''):
chars = []
for words in line:
b = words.rstrip(' \n')
chars.append(b)
grade.append(chars)
line = a1_file.readline()
推荐阅读
- c# - KeyDown 事件不会从 UWP 中的选定网格触发
- extjs - Extjs 6/7 树获得右键单击事件
- amazon-web-services - AWS CloudFormation:向其他 AWS 账户提供 CF 堆栈
- python - for 完成时打印数组内容
- c# - 是否有任何替代 MediaStreamType.photo 以获取 winforms 或 WPF 中的照片流?
- jupyter-notebook - 如何恢复已删除的 Jupyter 笔记本文件
- javascript - 保证哪些(如果有)JavaScript 操作不会导致 stackoverflow RangeErrors?
- tensorflow - 如何在不使用会话的情况下从 tf.size() 获取 int 值
- ruby-on-rails - 如何拒绝fastjson_api中的属性?
- swiftui - 不符合 String 协议 SwiftUI Picker View