首页 > 解决方案 > 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']]

标签: python

解决方案


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()

推荐阅读