如何在Python中替换嵌套列表中的元素

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

How to replace a element in a nested List in Python

问题

I can locate any listed content. In the example I locate 'q'. I manually mapped its index as [1][0][1][1]. Then I replaced it with 'z' and it works. My question is what is the magic to get the index(q) or Object Address(q) when the if() condition get set to True?

import ctypes
        
lis = [['a', ['b'], 'c'], [['d', ['p', ['q']]], 'e', 'f']]
idLis = id(lis)
if 'q' in str(lis):
    idLisContent = ctypes.cast(idLis, ctypes.py_object).value
    print("List Content: =", idLisContent)
    print("Index 0 =", idLisContent[0])
    print("Index 1 =", idLisContent[1])
    qId = id(idLisContent[1][0][1][1])
    print("Index Q =", ctypes.cast(qId, ctypes.py_object).value)
    idLisContent[1][0][1][1] = 'z'
    print("List Content: =", idLisContent)
exit(1)

Output:

List Content: = [['a', ['b'], 'c'], [['d', ['p', ['q']]], 'e', 'f']]
Index 0 = ['a', ['b'], 'c']
Index 1 = [['d', ['p', ['q']]], 'e', 'f']
Index Q = ['q']
List Content: = [['a', ['b'], 'c'], [['d', ['p', 'z']], 'e', 'f']]


<details>
<summary>英文:</summary>

I can locate any listed content. In the example I locate &#39;q&#39;. I manually mapped its index as `[1][0][1][1]`. Then I replaced it with &#39;z&#39; and it works. My question is what is the magic to get the index(q) or Object Address(q) when the if() condition get set to True?

     import ctypes
        
        lis = [[&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;], [[&#39;d&#39;, [&#39;p&#39;, [&#39;q&#39;]]], &#39;e&#39;, &#39;f&#39;]]
        idLis = id(lis)
        if &#39;q&#39; in str(lis):
            idLisContent = ctypes.cast(idLis, ctypes.py_object).value
            print(&quot;List Content: = &quot;, idLisContent)
            print(&quot;Index 0 = &quot;, idLisContent[0])
            print(&quot;Index 1 = &quot;, idLisContent[1])
            qId = id(idLisContent[1][0][1][1])
            print(&quot;Index Q = &quot;, ctypes.cast(qId, ctypes.py_object).value)
            idLisContent[1][0][1][1] = &#39;z&#39;
            print(&quot;List Content: = &quot;, idLisContent)
        exit(1)

Output:

    List Content: =  [[&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;], [[&#39;d&#39;, [&#39;p&#39;, [&#39;q&#39;]]], &#39;e&#39;, &#39;f&#39;]]
    Index 0 =  [&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;]
    Index 1 =  [[&#39;d&#39;, [&#39;p&#39;, [&#39;q&#39;]]], &#39;e&#39;, &#39;f&#39;]
    Index Q =  [&#39;q&#39;]
    List Content: =  [[&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;], [[&#39;d&#39;, [&#39;p&#39;, &#39;z&#39;]], &#39;e&#39;, &#39;f&#39;]]
    

</details>


# 答案1
**得分**: 0

我提供了一种真正的方法,用于替换多维数组的值,而不是首先将其转换为字符串,如[此答案](https://stackoverflow.com/a/75599730/12715723)中所述。当然,这些方法使用递归函数来获取多维数组中值的索引,并使用索引替换为另一个值。

```python
from copy import deepcopy

def getAllIndex(val, depth):
  if type(val) is str:
    allIndex[val] = deepcopy(depth)
  for i, j in enumerate(val):
    if type(val) is list:
      depth.append(i)
      getAllIndex(j, depth)
      depth.pop()
    
def getValue(val, index):
  if type(val) is str:
    return val
  else:
    return getValue(val[index[0]], index[1:]) 
    
def replaceValue(val, string, index):
  if len(index) == 1:
    val[index[0]] = string
  else:
    replaceValue(val[index[0]], string, index[1:]) 

lis = [['a', ['b'], 'c'], [['d', ['p', ['q']]], 'e', 'f']]

print("List Content: =", lis)
print("Index 0 =", lis[0])
print("Index 1 =", lis[1])

allIndex = {}
getAllIndex(lis, []) # 返回 { 'a': [0, 0], 'b': [0, 1, 0], 'c': [0, 2], 'd': [1, 0, 0], 'p': [1, 0, 1, 0], 'q': [1, 0, 1, 1, 0], 'e': [1, 1], 'f': [1, 2] }
indexQ = allIndex['q'] # 获取 'q' 的索引

print("Index Q =", indexQ) # 'q' 的索引 = [1][0][1][1][0] 表示为 [1, 0, 1, 1, 0]
print("Value of", indexQ, "=", getValue(lis, indexQ)) # 获取 lis[1][0][1][1][0] 的值

replaceValue(lis, 'z', indexQ) # 使用 'q' 的索引替换特定值,例如 'q' => 'z'

print("List Content: =", lis)

输出将是:

List Content: =  [['a', ['b'], 'c'], [['d', ['p', ['q']]], 'e', 'f']]
Index 0 =  ['a', ['b'], 'c']
Index 1 =  [['d', ['p', ['q']]], 'e', 'f']
Index Q =  [1, 0, 1, 1, 0]
Value of [1, 0, 1, 1, 0] = q
List Content: =  [['a', ['b'], 'c'], [['d', ['p', ['z']]], 'e', 'f']]
英文:

I offer a true method to replace the value of a multidimensional array instead of converting it to a string first as stated in this answer. Of course, these ways use a recursive function to get the index of the value in the multidimensional array and to replace that with another value using the index.

from copy import deepcopy

def getAllIndex(val, depth):
  if type(val) is str:
    allIndex[val] = deepcopy(depth)
  for i, j in enumerate(val):
    if type(val) is list:
      depth.append(i)
      getAllIndex(j, depth)
      depth.pop()
    
def getValue(val, index):
  if type(val) is str:
    return val
  else:
    return getValue(val[index[0]], index[1:]) 
    
def replaceValue(val, string, index):
  if len(index) == 1:
    val[index[0]] = string
  else:
    replaceValue(val[index[0]], string, index[1:]) 

lis = [[&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;], [[&#39;d&#39;, [&#39;p&#39;, [&#39;q&#39;]]], &#39;e&#39;, &#39;f&#39;]]

print(&quot;List Content: = &quot;, lis)
print(&quot;Index 0 = &quot;, lis[0])
print(&quot;Index 1 = &quot;, lis[1])

allIndex = {}
getAllIndex(lis, []) # returns {&#39;a&#39;: [0, 0], &#39;b&#39;: [0, 1, 0], &#39;c&#39;: [0, 2], &#39;d&#39;: [1, 0, 0], &#39;p&#39;: [1, 0, 1, 0], &#39;q&#39;: [1, 0, 1, 1, 0], &#39;e&#39;: [1, 1], &#39;f&#39;: [1, 2]}
indexQ = allIndex[&#39;q&#39;] # get index of &#39;q&#39;

print(&quot;Index Q = &quot;, indexQ) # index of &#39;q&#39; = [1][0][1][1][0] represent as [1, 0, 1, 1, 0]
print(&quot;Value of&quot;,indexQ,&quot;=&quot;,getValue(lis, indexQ)) # get value of lis[1][0][1][1][0]

replaceValue(lis, &#39;z&#39;, indexQ) # replace specific value e.g. &#39;q&#39; =&gt; &#39;z&#39; with index of &#39;q&#39;

print(&quot;List Content: = &quot;, lis)

The output will be:

List Content: =  [[&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;], [[&#39;d&#39;, [&#39;p&#39;, [&#39;q&#39;]]], &#39;e&#39;, &#39;f&#39;]]
Index 0 =  [&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;]
Index 1 =  [[&#39;d&#39;, [&#39;p&#39;, [&#39;q&#39;]]], &#39;e&#39;, &#39;f&#39;]
Index Q =  [1, 0, 1, 1, 0]
Value of [1, 0, 1, 1, 0] = q
List Content: =  [[&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;], [[&#39;d&#39;, [&#39;p&#39;, [&#39;z&#39;]]], &#39;e&#39;, &#39;f&#39;]]

答案2

得分: -1

只需将其转换为字符串并将 'q' 替换为 'z'。

lis = [['a', ['b'], 'c'], [['d', ['p', ['q']]], 'e', 'f']]

str_lis = str(lis).replace('q', 'z');

print str_lis;

英文:

Just convert it to string and replace 'q' to 'z'

lis = [[&#39;a&#39;, [&#39;b&#39;], &#39;c&#39;], [[&#39;d&#39;, [&#39;p&#39;, [&#39;q&#39;]]], &#39;e&#39;, &#39;f&#39;]]

str_lis = str(lis).replace(&#39;q&#39;, &#39;z&#39;);

print  str_lis;

huangapple
  • 本文由 发表于 2023年3月1日 12:47:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599667.html
匿名

发表评论

匿名网友

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

确定