如何通过向现有列表追加元素在Python中创建嵌套列表

huangapple go评论63阅读模式
英文:

How to create a nested list in python by appending to an existing list

问题

以下是代码部分的翻译,其他内容将被省略:

for i in range(0, len(address_list):
   
    # 一些代码被跳过,其中 file_path_simple 每次都会获得新的值
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('\n')
            temp_list.append(ln)
        fp.close()

    for j in temp_list:
        address_list[i].append(j)

这是导致错误的代码部分:

Traceback (most recent call last): File "[path_redacted]\tracer.py", line 155, in <module> 
    address_list[i].append([]) 
AttributeError: 'str' object has no attribute 'append' 

完整的代码很长,但希望这部分能够提供更好的理解:

address_list = []
temp_list = []
G = nx.Graph()
address_list.append(address)

# 添加根节点
G.add_node(address_list[0])

for i in range(0, len(address_list)):
    # 用于测试的打印语句
    print(address_list[i])
    
    if i == target:
        tracePath(address, address_list[i])
    
    # 查询地址
    txQuery(address_list[i])
    parser()

    # 将输出写入 temp_list,它将成为嵌套列表
    file_path_simple = r'Z:\[path_redacted]\tx_list_simple.txt'
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('\n')
            temp_list.append(ln)
        fp.close()

    # 创建与关联地址的嵌套列表
    address_list[i].append([])
    for j in temp_list:
        address_list[i].append(j)

    # 创建父节点的子节点,该父节点已被查询
    for i in address_list[0][i]:
        G.add_node(i)
        G.add_edge(*[address_list[0], i])
        address_list.append(i)
    
    temp_list.clear()
英文:

I have a list called address_list and I want to iterate through it. Each value in the address_list I iterate through is run through another function which will return a new list called temp_list. I then want to nest the values of temp_list under the original value in address_list before moving on and doing the same thing to the next value in address_list.

Essentially it should look like this (with the address_list index on the left and the temp_list on the right):

[0] - [1,2,3]

[1] - [1,5,6,7,8,35]

[2] - [3,543,34,84,3,8,53]

This is the code I am trying to use:

for i in range(0,len(address_list)):
   
    #some code skipped where file_path_simple gets new values each time
    with open(file_path_simple, &#39;r&#39;) as fp:
        for ln in fp:
            ln = ln.strip(&#39;\n&#39;)
            temp_list.append(ln)
        fp.close()

    for j in temp_list:
        address_list[i].append(j)

This is giving me the following error:

Traceback (most recent call last): File &quot;z:[path_redacted]\tracer.py&quot;, line 155, in &lt;module&gt; 
    address_list[i].append([]) 
AttributeError: &#39;str&#39; object has no attribute &#39;append&#39; 

The full code is LONG but hopefully this chunk will give a better idea:

address_list = []
temp_list = []
G = nx.Graph()
address_list.append(address)

#adds the root
G.add_node(address_list[0])

for i in range(0,len(address_list)):
    #print for testing purposes
    print(address_list[i])
    
    if i == target:
        tracePath(address, address_list[i])
    
    #query the address
    txQuery(address_list[i])
    parser()

    #write output to temp_list which will be the nested list
    file_path_simple = r&#39;Z:\[path_redacted]\tx_list_simple.txt&#39;
    with open(file_path_simple, &#39;r&#39;) as fp:
        for ln in fp:
            ln = ln.strip(&#39;\n&#39;)
            temp_list.append(ln)
        fp.close()

    #create the nested list for associated addresses
    address_list[i].append([])
    for j in temp_list:
        address_list[i].append(j)

    #create the children of the parent node which was queried
    for i in address_list[0][i]:
        G.add_node(i)
        G.add_edge(*[address_list[0],i])
        address_list.append(i)
    
    temp_list.clear()

答案1

得分: 1

从我了解的情况来看,您想要将文件读入一个列表,然后将该列表放入另一个列表中?您不需要在循环中执行这个操作。

但是,您仍然可以在address_list从该文件中填充后之后循环遍历它。

G = nx.Graph()
G.add_node(address)

address_list = []

file_path_simple = r'Z:\[path_redacted]\tx_list_simple.txt'
with open(file_path_simple, 'r') as fp:
    temp_list = [ln.strip('\n') for ln in fp]
    address_list.append(temp_list)

for i, a in enumerate(address_list):
    if i == target:
        tracePath(address, a)
    
    # query the address
    txQuery(a)
    parser()
英文:

From what I can tell, you want to read a file into a list, then put that list into another one? You don't need to do that in a loop

But you can still loop over the address_list after it is populated from that file

G = nx.Graph()
G.add_node(address)

address_list = []

file_path_simple = r&#39;Z:\[path_redacted]\tx_list_simple.txt&#39;
with open(file_path_simple, &#39;r&#39;) as fp:
    temp_list = [ln.strip(&#39;\n&#39;) for ln in fp]
    address_list.append(temp_list)

for i, a in enumerate(address_list):
    if i == target:
        tracePath(address, a)
    
    # query the address
    txQuery(a)
    parser()

答案2

得分: 0

如果我理解正确,您想用temp_list替换值i处的元素?
如果是这样,以下是一些代码(未经测试):
代码1:

for i, _ in enumerate(address_list): 
    """enumerate将您的列表转换为一个包含索引和值的元组的列表 -> enumerate(["a", "b", "c"]) == [(0, "a"), (1, "b"), (2, "c")]"""
    temp_list = [] # 我认为您不需要保留旧值
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('\n')
            temp_list.append(ln)
        # 不需要关闭文件,因为在“with”语句结束时,文件会自动关闭
    address_list[i] = [] # 用列表替换旧值,这样您就可以进行附加
    for j in temp_list:
        address_list[i].append(j)

(未经测试)代码2:

for i, _ in enumerate(address_list):
    temp_list = []
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('\n')
            temp_list.append(ln)
    address_list[i] = temp_list

不要担心我的英语水平,
Flayme

英文:

If I understand, you wan't to replace the element at the value i by temp_list?
If it's that here is some code (not tested):
code 1:

for i, _ in enumerate(address_list): 
    &quot;&quot;&quot;enumerate take your list and transform it into a list contening a tuple contening the index and the value -&gt; enumerate([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]) == [(0, &quot;a&quot;), (1, &quot;b&quot;), (2, &quot;c&quot;)]&quot;&quot;&quot;
    temp_list = [] # I think you don&#39;t need to have the old value
    with open(file_path_simple, &#39;r&#39;) as fp:
        for ln in fp:
            ln = ln.strip(&#39;\n&#39;)
            temp_list.append(ln)
        # don&#39;t need to close because at the end of the &quot;with&quot; statement
        #the file is automaticly close
address_list[i] = [] # replace the old value by a list so you can 
                     #append
for j in temp_list:
    address_list[i].append(j)

(not tested) code 2:

for i, _ in enumerate(address_list):
    temp_list = []
    with open(file_path_simple, &#39;r&#39;) as fp:
        for ln in fp:
            ln = ln.strip(&#39;\n&#39;)
            temp_list.append(ln)
    address_list[i] = temp_list

don't mind my poor english,
Flayme

huangapple
  • 本文由 发表于 2023年2月24日 07:50:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定