【问题标题】:Update the nth element of the nth element in nested lists更新嵌套列表中第 n 个元素的第 n 个元素
【发布时间】:2013-10-25 11:45:35
【问题描述】:

列表的列表让我很恼火。我已经进行了大量研究,试图找到如何更新列表 python 数据结构列表中第 n 个列表的第 n 个元素。我看到很多关于更新第 n 个元素或将列表合并到现有列表中的建议,但没有关于更新嵌套列表中的特定元素的建议。

我的实际代码通读文件搜索 tid:somestring 然后将 tid:somestring 添加到集合中。我现在想遍历该集合并将该值设为每次出现的第 0 个 y。我在代码中的下一步将在第 1 个 y 中添加另一个搜索项,以获取我之前放置在第 0 个 y 位置的相应 tid 值(对于剩余的搜索值,依此类推)。我计划用一个计数器递增以移动 x 的索引值......基本上,我需要更新一个二维数组。 y 轴上有 9 个值。 x 轴取决于 tid:somestring 的唯一实例数,每个文件有 10,000 个或更多。

如何更新/插入或以其他方式更改列表中第 n 个列表的第 n 项?

samlfile="2013-08-18 22:47:55,248 tid:b7c31fbac DEBUG" #I have a file with 10000+ "tid"
tidset = set()
tidcount = len(tidset)
tidassert = [[0 for x in range(tidcount)] for y in range(9)]
xcount = 0


for line in samlfile:

    if "tid:" in line:
        str=line
        tid = re.search(r'(tid:.*?)(?= )', str)
        if tid.group() not in tidset:
            tidset.add(tid.group())
            tid = tid.group()
            for tid in tidset:
                tidassert[xcount][0] = tid
            xcount = xcount + 1

        print tidassert

【问题讨论】:

    标签: python arrays list multidimensional-array


    【解决方案1】:
    try:
    
        _list[n][n] = 'new val'
    
    except IndexError:
    
        print 'No such index'
    

    【讨论】:

    • 感谢您的共鸣,但我基本上是在我拥有的代码中这样做的。 tidassert[xcount][0] = tid,没有错误处理。除非,我误解了这个建议。如果是这样,你能详细说明吗?
    • 你的moto是update/insert or otherwise change the nth item of the nth list,这个会尝试改变值,如果没有indicesinaccessible它会抛出IndexError
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 2012-07-09
    • 1970-01-01
    • 2018-05-27
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多