2012-11-11 18 views
-2

可能重复:
list of list of str如何从一个文本获得包含每一行的字母列表的列表

我犯了一个代码返回列表的名单,这些的列表包含一个单词中的所有字母,这些单词是在一个文本中,但是在打开文本文件并阅读它之后,我们单独列出了每一行。

例如:

listof(["hello stack overflow community \n", "i like this site \n", "thank you \n"]) 

结果是:

[['h', 'e', 'l', 'l', 'o'], ['s', 't', 'a', 'c', 'k'], ['o', 'v', 'e', 'r', 'f', 'l', 'o', 'w'], ['c', 'o', 'm', 'm', 'u', 'n', 'i', 't', 'y'], ['i'], ['l', 'i', 'k', 'e'], ['t', 'h', 'i', 's'], ['s', 'i', 't', 'e'], ['t', 'h', 'a', 'n', 'k'], ['y', 'o', 'u']] 

和我做的代码如下:

def listof(listoflines): 
    board_list = [] 
    board = [] 
    for element in listoflines: 
     board_list.append((element.strip('\n')).split()) 
    for member in board_list: 
    for i in range(len(member)): 
     board.append(list(member[i])) 

    return board 

我知道代码看起来很丑,所以是有更好的方式以更专业的方式完成这项任务吗? ,并且能够更长时间地记住它?

感谢

回答

1
 python 3.2 
    a=["hello stack overflow community \n", "i like this site \n", "thank you \n"] 
    [[list(v) for v in i.split()] for i in a] 
+0

谢谢拉通,我喜欢你的代码,它是真正的优雅。 – mazlor

0

试试这个示例:

[list(word.strip()) for word in [line.rstrip('\n').split() for line in text]] 
相关问题