猿问

将列表元素附加到另一个返回空列表/元组的列表的函数

我有一个包含三行的文本文件,我将其拆分为一个名为cleanedFileListusing的列表列表function1():


你好,1


再次,2


世界,3


运行后function1(),打印时看起来像这样,这就是打印fileOutput得到的:


[[hello, 1], [again, 2], [world, 3]]

我基本上是在尝试创建一个function2()可以cleanedFileList根据第二个位置的数值将单词附加到三个单独的列表中的方法。例如,[hello,1]将作为“hello”附加到,l1因为它携带值 1,在它的第二个位置cleanedFileList...同样,[again, 2]将作为“再次”附加到l2因为值 2,在它的第二个位置


fileInput = open('keywords.txt', 'r')



l1 = []

l2 = []

l3 = []



def function1(file):

        cleanedFileList = []

        for line in file:

            cleanedFileList.append(line.strip().split(','))

        return cleanedFileList


fileOutput = function1(fileInput)    


def function2(file):

       for i in range(len(file)):

            if file[i][1] == 1:

                l1.append(file[i][0])

            if file[i][1] == 2:

                l2.append(file[i][0])

            if file[i][1] == 3:

                l3.append(file[i][0])

       return l1, l2, l3



listOutput = function2(fileOutput)

print(listOutput)

print(l1)

但是,当我运行上面的代码时,我得到一个空元组(来自 in 的 return 语句function2()和一个空列表(来自尝试打印l1):


([], [], [])

[]


拉丁的传说
浏览 154回答 2
2回答

肥皂起泡泡

看来,您在 fileOutput 中有字符串,而不是整数。所以“1”!= 1。你也可以在你的字符串中看到空格:'1'、'2'等。

慕娘9325324

与动态创建列表相比,将元素存储到字典中会更好。from collections import defaultdictlst = [['hello', '1'], ['again', '2'], ['world', '3'], ['good', '1'], ['morning', '3']]d = defaultdict(list)for x in lst:&nbsp; &nbsp; d[x[1]].append(x[0])print(d)# defaultdict(<class 'list'>, {'1': ['hello', 'good'], '2': ['again'], '3': ['world', 'morning']})现在,您可以访问所有1元素 as d['1'],所有2元素 asd['2']等等......例如:>>> d['1']['hello', 'good']
随时随地看视频慕课网APP

相关分类

Python
我要回答