我有一个结构如下的文件
word1a word2a
word1b word2b
word1c word2c
word1d word2d
\n -> Empty Line
word11a word21a
word11b word21b
word11c word21c
\n -> Empty Line
word12a word22a
word12b word22b
word12c word22c
word12d word22d
\n -> Empty Line
\n -> Empty Line
我需要创建两个单独的列表
wordList_1 = [[word1a,word1b,word1c,word1d],[word11a,word11b,word11c],[word12a,word12b,word12c,word12d]]
wordList_2 = [[word2a,word2b,word2c,word2d],[word21a,word21b,word21c],[word22a,word22b,word22c,word22d]]
我如何有效地做到这一点?你知道吗
我想出了如下的解决办法,但我知道我在实现目标方面做得不好。所以,请看下面的代码,让我知道我可以改变它,以达到预期的结果。你知道吗
def fun(fName):
Create two empty lists, words1 = [] and words2 = []
with open(fname) as f:
all_the_lines_in_file = f.read()
lines = all_the_lines_in_file.split("\n\n") //Split The line based on new line
for line in lines:
l = line.split("\n")
Create two empty lists, w1 = [] and w2 = []
for words in l:
if(len(words)>1):
w = words.split()
w1.append(w[0])
w2.append(w[1])
words1.append(w1)
words2.append(w2)
也许比你的尝试更有效率:
输出:
相关问题 更多 >
编程相关推荐