【问题标题】:Access tuple elemens in a nested list python访问嵌套列表python中的元组元素
【发布时间】:2020-06-16 09:17:08
【问题描述】:

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

[('dad', 'mom', 'test1.txt')]
[('brother', 'sister', 'test2.txt')]
[('uncle', 'aunty', 'test3.txt')]
[('grandpa', 'grandma', 'test4.txt')]

我想一次访问一个列表,例如,我从 1st list index[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..

上面的代码没有按照要求给我正确的输出。有人可以帮助我使用这种方法吗?

谢谢!

【问题讨论】:

    标签: python python-3.x list for-loop tuples


    【解决方案1】:

    这就是我的做法:

    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
    

    我在length of the list: len(lis)范围 中迭代了list 的元素。这样j 将采用值0, 1, 2, 3。然后我使用了for loop,它遍历列表的元素。因此,jlis 的元素的值假定为 lis[0], lis[1], lis[2], lis[3]

    现在j 具有列表元素的值,我们可以使用i[(integer)] 并访问列表元素的元素,即"dad", "mom", "test1.txt" 等。

    因此我们可以将条件应用于i[0] or i[1] 等。

    例如:

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

    希望对您有所帮助!

    【讨论】:

      【解决方案2】:

      由于您阅读了 4 次正确的文件名,因此不清楚您有什么问题

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

      【讨论】:

        【解决方案3】:

        尽量不要使用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
        

        【讨论】:

        • 如果我使用您的方法,例如 data[0][2],它会给出一个值 '1' 并表示找不到文件。 @Venkat
        • 抱歉,我已经编辑了,您现在可以检查一下吗
        • 对不起这也不起作用@Trilok,如果你知道它的列表意味着你能指导我吗?我听说嵌套列表比元组列表好。
        • 你能把你的数据长什么样子发给我吗?我所做的是由包含元组的列表组成的列表,如果那不是您要查找的内容,请告诉我吗?
        【解决方案4】:
        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-16
          相关资源
          最近更新 更多