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

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

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

问题

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

  1. for i in range(0, len(address_list):
  2. # 一些代码被跳过,其中 file_path_simple 每次都会获得新的值
  3. with open(file_path_simple, 'r') as fp:
  4. for ln in fp:
  5. ln = ln.strip('\n')
  6. temp_list.append(ln)
  7. fp.close()
  8. for j in temp_list:
  9. address_list[i].append(j)

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

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

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

  1. address_list = []
  2. temp_list = []
  3. G = nx.Graph()
  4. address_list.append(address)
  5. # 添加根节点
  6. G.add_node(address_list[0])
  7. for i in range(0, len(address_list)):
  8. # 用于测试的打印语句
  9. print(address_list[i])
  10. if i == target:
  11. tracePath(address, address_list[i])
  12. # 查询地址
  13. txQuery(address_list[i])
  14. parser()
  15. # 将输出写入 temp_list,它将成为嵌套列表
  16. file_path_simple = r'Z:\[path_redacted]\tx_list_simple.txt'
  17. with open(file_path_simple, 'r') as fp:
  18. for ln in fp:
  19. ln = ln.strip('\n')
  20. temp_list.append(ln)
  21. fp.close()
  22. # 创建与关联地址的嵌套列表
  23. address_list[i].append([])
  24. for j in temp_list:
  25. address_list[i].append(j)
  26. # 创建父节点的子节点,该父节点已被查询
  27. for i in address_list[0][i]:
  28. G.add_node(i)
  29. G.add_edge(*[address_list[0], i])
  30. address_list.append(i)
  31. 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:

  1. for i in range(0,len(address_list)):
  2. #some code skipped where file_path_simple gets new values each time
  3. with open(file_path_simple, &#39;r&#39;) as fp:
  4. for ln in fp:
  5. ln = ln.strip(&#39;\n&#39;)
  6. temp_list.append(ln)
  7. fp.close()
  8. for j in temp_list:
  9. address_list[i].append(j)

This is giving me the following error:

  1. Traceback (most recent call last): File &quot;z:[path_redacted]\tracer.py&quot;, line 155, in &lt;module&gt;
  2. address_list[i].append([])
  3. 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:

  1. address_list = []
  2. temp_list = []
  3. G = nx.Graph()
  4. address_list.append(address)
  5. #adds the root
  6. G.add_node(address_list[0])
  7. for i in range(0,len(address_list)):
  8. #print for testing purposes
  9. print(address_list[i])
  10. if i == target:
  11. tracePath(address, address_list[i])
  12. #query the address
  13. txQuery(address_list[i])
  14. parser()
  15. #write output to temp_list which will be the nested list
  16. file_path_simple = r&#39;Z:\[path_redacted]\tx_list_simple.txt&#39;
  17. with open(file_path_simple, &#39;r&#39;) as fp:
  18. for ln in fp:
  19. ln = ln.strip(&#39;\n&#39;)
  20. temp_list.append(ln)
  21. fp.close()
  22. #create the nested list for associated addresses
  23. address_list[i].append([])
  24. for j in temp_list:
  25. address_list[i].append(j)
  26. #create the children of the parent node which was queried
  27. for i in address_list[0][i]:
  28. G.add_node(i)
  29. G.add_edge(*[address_list[0],i])
  30. address_list.append(i)
  31. temp_list.clear()

答案1

得分: 1

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

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

  1. G = nx.Graph()
  2. G.add_node(address)
  3. address_list = []
  4. file_path_simple = r'Z:\[path_redacted]\tx_list_simple.txt'
  5. with open(file_path_simple, 'r') as fp:
  6. temp_list = [ln.strip('\n') for ln in fp]
  7. address_list.append(temp_list)
  8. for i, a in enumerate(address_list):
  9. if i == target:
  10. tracePath(address, a)
  11. # query the address
  12. txQuery(a)
  13. 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

  1. G = nx.Graph()
  2. G.add_node(address)
  3. address_list = []
  4. file_path_simple = r&#39;Z:\[path_redacted]\tx_list_simple.txt&#39;
  5. with open(file_path_simple, &#39;r&#39;) as fp:
  6. temp_list = [ln.strip(&#39;\n&#39;) for ln in fp]
  7. address_list.append(temp_list)
  8. for i, a in enumerate(address_list):
  9. if i == target:
  10. tracePath(address, a)
  11. # query the address
  12. txQuery(a)
  13. parser()

答案2

得分: 0

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

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

(未经测试)代码2:

  1. for i, _ in enumerate(address_list):
  2. temp_list = []
  3. with open(file_path_simple, 'r') as fp:
  4. for ln in fp:
  5. ln = ln.strip('\n')
  6. temp_list.append(ln)
  7. 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:

  1. for i, _ in enumerate(address_list):
  2. &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;
  3. temp_list = [] # I think you don&#39;t need to have the old value
  4. with open(file_path_simple, &#39;r&#39;) as fp:
  5. for ln in fp:
  6. ln = ln.strip(&#39;\n&#39;)
  7. temp_list.append(ln)
  8. # don&#39;t need to close because at the end of the &quot;with&quot; statement
  9. #the file is automaticly close
  10. address_list[i] = [] # replace the old value by a list so you can
  11. #append
  12. for j in temp_list:
  13. address_list[i].append(j)

(not tested) code 2:

  1. for i, _ in enumerate(address_list):
  2. temp_list = []
  3. with open(file_path_simple, &#39;r&#39;) as fp:
  4. for ln in fp:
  5. ln = ln.strip(&#39;\n&#39;)
  6. temp_list.append(ln)
  7. 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:

确定