Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表与txt文件中的列进行比较_Python_List_Comparison - Fatal编程技术网

Python 将列表与txt文件中的列进行比较

Python 将列表与txt文件中的列进行比较,python,list,comparison,Python,List,Comparison,我试图用python阅读文件的第5列。如果第三列与“Plop”匹配,我将第三列存储在列表1中,否则如果第五列与“toto”匹配,我将第三列存储在列表2中。然后我所做的就是检查两个列表中每个元素的长度。当我运行代码时,出现以下错误: if word1 in columns[:4] ^ SyntaxError: invalid syntax 我的代码如下: word1=['Popo'] word2=['toto'] aList1 = list() aLi

我试图用python阅读文件的第5列。如果第三列与“Plop”匹配,我将第三列存储在列表1中,否则如果第五列与“toto”匹配,我将第三列存储在列表2中。然后我所做的就是检查两个列表中每个元素的长度。当我运行代码时,出现以下错误:

if word1 in columns[:4]
                      ^
SyntaxError: invalid syntax
我的代码如下:

word1=['Popo']
word2=['toto']
aList1 = list()
aList = list()

for line in open("test.txt"):
    columns = line.split(" ")
 #columns.lookup([toto])
    if word1 in (columns[:4]):
        aList1.insert(columns[:2])
    if word2 in (columns[:4]):
        aList.insert(columns[:2])

#print '\n'.join(aList1)

for entry in aList1:
    try:
        l = len(entry)
        print "Length of", entry, "is", l
    except:
        print "Element", entry, "has no defined length"

for entry in aList:
    try:
        l = len(entry)
        print "Length of", entry, "is", l
    except:
        print "Element", entry, "has no defined length"

您最后缺少了,应该是:

if word1 in columns[:4]:

您最后缺少了,应该是:

if word1 in columns[:4]:

你的代码没有正确的缩进@Arman我的代码在最后2个for循环时有正确的缩进,只是在stackoverflow上我必须为每个循环实际输入4个空格line@user3022048只需复制/粘贴整个内容,突出显示所有内容,然后单击编辑器中的
{}
按钮,或者使用ctrl+kNo,您可以使用
Ctrl+k
获得正确的代码格式!我的代码已经缩进了,谢谢!你的代码没有正确的缩进@Arman我的代码在最后2个for循环时有正确的缩进,只是在stackoverflow上我必须为每个循环实际输入4个空格line@user3022048只需复制/粘贴整个内容,突出显示所有内容,然后单击编辑器中的
{}
按钮,或者使用ctrl+kNo,您可以使用
Ctrl+k
获得正确的代码格式!我的代码已经缩进了,谢谢!谢谢你的回答。它解决了我的语法错误。谢谢你的回答。它解决了我的语法错误。