python - 将列表元素附加到另一个列表的函数返回空列表/元组
问题描述
我有一个包含三行的文本文件,我将其拆分为一个名为cleanedFileList
using的列表列表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
):
([], [], [])
[]
解决方案
将元素存储到字典中比动态创建列表更好。
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']
推荐阅读
- python - PythonError:FileNotFoundError:[Errno 2]没有这样的文件或目录:'Text.txt'
- mule - 用于解析器编译的 ANTLR 运行时版本 4.7.2 与当前运行时版本 4.5.1 不匹配
- python - 在 pcolor 图上添加 $y=x$ 行:它不起作用
- c# - selenium chromedriver 抛出版本错误,但版本匹配
- docker - 在 plesk 的 docker 容器上运行 keycloak 服务器的问题
- python - Django Python - 迁移后已删除属性上的 SQLDecodeError
- r - 为什么 geom_smooth 没有出现在分组数据框中?
- time-complexity - 广度优先或深度优先
- javascript - 如何递归地在树中插入项目
- python - 如何使用Python从excel中的列中获取子字符串?