Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.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 访问嵌套列表中的元组元素_Python_Python 3.x_List_For Loop_Tuples - Fatal编程技术网

Python 访问嵌套列表中的元组元素

Python 访问嵌套列表中的元组元素,python,python-3.x,list,for-loop,tuples,Python,Python 3.x,List,For Loop,Tuples,我是python新手,我有一个带有嵌套列表的列表,其中包含元组,如下所示 [('dad', 'mom', 'test1.txt')] [('brother', 'sister', 'test2.txt')] [('uncle', 'aunty', 'test3.txt')] [('grandpa', 'grandma', 'test4.txt')] 我想一次访问一个列表,例如,我从第一个列表索引[2]打开test1.txt文件,如果字符串'dad'和'mom'存在,则过滤文件,并对text2.

我是python新手,我有一个带有嵌套列表的列表,其中包含元组,如下所示

[('dad', 'mom', 'test1.txt')]
[('brother', 'sister', 'test2.txt')]
[('uncle', 'aunty', 'test3.txt')]
[('grandpa', 'grandma', 'test4.txt')]
我想一次访问一个列表,例如,我从第一个列表索引[2]打开test1.txt文件,如果字符串'dad'和'mom'存在,则过滤文件,并对text2.txt文件进行同样的读取,如果'brother'和'sister'存在,则读取并过滤

我有以下代码:

for data in list:
    file= data[2]
    text_file= open(file,'r').readlines()
    if data[0], data[1] in text_file:
    #do something..
以上代码没有按照要求提供正确的输出。有人能帮我解决这个问题吗


谢谢

不清楚您出了什么问题,因为您读取了4次正确的文件名


我想如果你用break语句找到你想要的东西,你必须退出for循环。

尽量不要使用像
list

L=[[('dad', 'mom', 'test1.txt')],
[('brother', 'sister', 'test2.txt')],
[('uncle', 'aunty', 'test3.txt')],
[('grandpa', 'grandma', 'test4.txt')]]
for data in L:
  f=data[0][2]
  file1=open(f,"r")
  text_file=file1.read()
  if(data[0][0] and data[0][1] in text_file):
     #do something

我就是这样做的:

lis=[[('dad', 'mom', 'test1.txt')],
    [('brother', 'sister', 'test2.txt')],
    [('uncle', 'aunty', 'test3.txt')],
    [('grandpa', 'grandma', 'test4.txt')]]
for i in range(len(lis)):
    for j in lis[j]:
        f = open(i[2])
        lines = f.read()
        if i[0] in lines and i[1] in lines:
            #do sth
我已经在列表长度len(lis)的范围内迭代了列表的元素。这样
j
获取值
0,1,2,3
。然后我使用了一个循环,循环遍历列表中的元素。因此,
j
假定
lis
元素的值为
lis[0]、lis[1]、lis[2]、lis[3]

既然
j
具有列表元素的值,我们就可以使用
i[(整数)]
并访问列表元素的元素,即
“dad”、“mom”、“test1.txt”

因此,我们可以将条件应用于
i[0]或i[1]

例如:

if i[0] == "dad":
    print(something)

希望这对你有帮助

如果我对示例数据[0][2]使用您的方法,则会给出一个值“1”,并表示找不到文件@VenkatHey很抱歉,我已经编辑了。请现在检查一下。对不起,这也不起作用@Trilok,如果你知道它的列表意味着什么,你能指导我吗?我听说嵌套列表比元组列表好。你能告诉我你的数据是什么样子的吗。我所做的是由包含元组的列表组成的列表,如果这不是您要找的,请告诉我好吗?
lis=[[('dad', 'mom', 'test1.txt')],
    [('brother', 'sister', 'test2.txt')],
    [('uncle', 'aunty', 'test3.txt')],
    [('grandpa', 'grandma', 'test4.txt')]]
for i in lis:
    data=i[0][2]
    f=open(data,'r')
    file=f.read()
    if (i[0][0] and i[0][1])in file:
        pass