首页 > 解决方案 > 将列表元素附加到另一个列表的函数返回空列表/元组

问题描述

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

你好,1

再次,2

世界,3

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

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

我实际上是在尝试创建一个function2()可以cleanedFileList根据第二个位置的数值将单词附加到三个单独的列表中的方法。例如,[hello,1]将被附加为“你好”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)

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

([], [], [])
[]

标签: pythonlistfunctiontuples

解决方案


将元素存储到字典中比动态创建列表更好。

from collections import defaultdict

lst = [['hello', '1'], ['again', '2'], ['world', '3'], ['good', '1'], ['morning', '3']]

d = defaultdict(list)

for x in lst:
    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']

推荐阅读