在python中,我应该如何使用函数将文件读入二维列表后,不要让二维列表为空

Posted

技术标签:

【中文标题】在python中,我应该如何使用函数将文件读入二维列表后,不要让二维列表为空【英文标题】:In python how am I supposed to, after reading the file into a 2D list, using a function, not let the 2D list empty 【发布时间】:2017-11-23 18:21:24 【问题描述】:

我读入了一个文本文件,格式如下: 奥拉,2 奥拉,4 奥拉,6

我使用删除列表中所有备用元素的读取功能读取此文件:

import csv

def read(name,practicef):
    temp=[]
    name=name+".txt"
    practicef = list(csv.reader(open(name,"r")))
    print(practicef)
    print(len(practicef))
    temp=practicef
    practicef=[]
    for item in temp:
        if item!=[]:
            practicef.append(item)
            print(practicef)
    return practicef

然后当我想将列表中的元素与我的密码进行比较时,列表是空的,我只是想知道为什么会这样做以及如何避免它。 整个代码按顺序排列在一起是:

import csv

def read(name,practicef):
    temp=[]
    name=name+".txt"
    practicef = list(csv.reader(open(name,"r")))
    print(practicef)
    print(len(practicef))
    temp=practicef
    practicef=[]
    for item in temp:
        if item!=[]:
            practicef.append(item)
            print(practicef)
    return practicef



practicef=()
name="lollington"
read(name,practicef)
use=input("use")
pw=input("pw")
print(len(practicef))

for i in range(0,len(practicef)):
    print(use,pw)
    print(practicef[i][0],practicef[i][1])
    if use== practicef[i][0] and pw == practicef[i][1]:
        print("successful login")

【问题讨论】:

【参考方案1】:

你想要做的事情有点难,但是你实际上并没有使用你的函数的结果。

practicef = read(name,practicef)

让你更接近你想去的地方?

这是我更改后的输出(在打印件上添加了一些额外内容,以便更容易查看它们的来源):

in read [['ola', '2 ola', '4 ola', '6']]
len in read 1
[['ola', '2 ola', '4 ola', '6']]

use: ola

pw: 2
outer list len after fcn call: 1
uid ola pw 2
ola 2 ola

【讨论】:

是的,现在可以正常使用了,谢谢

以上是关于在python中,我应该如何使用函数将文件读入二维列表后,不要让二维列表为空的主要内容,如果未能解决你的问题,请参考以下文章

我应该使用哪个函数将非结构化文本文件读入 R? [关闭]

用python处理csv文件,最好可以将里面的文本信息转成一个二维数组的形式,具体如下

VB.NET:将 CSV 文件读入二维数组

将文本文件读入二维向量。 C++

如何将文件读入 Python 中的列表? [复制]

C++ 图像处理 - 将图像文件读入二维数组