[英]finding and replacing elements in a multidimensional list (python)
類似於這個問題: 查找和替換列表中的元素(python)但使用多維數組。 例如,我想用 0 替換所有 N:
list =
[['N', 0.21],
[-1, 6.6],
['N', 34.68]]
我想將其更改為:
list =
[[0, 0.21],
[-1, 6.6],
[0, 34.68]]
您可以使用嵌套列表理解:
l = [['N', 0.21], [-1, 6.6], ['N', 34.68]]
new_l = [[0 if b == 'N' else b for b in i] for i in l]
輸出:
[[0, 0.21], [-1, 6.6], [0, 34.68]]
試試這個:
for l in list:
while 'N' in l:
l[l.index('N')]=0
不要使用列表作為變量名:
list1 =[['N', 0.21],
[-1, 6.6],
['N', 34.68]]
[j.__setitem__(ii,0) for i,j in enumerate(list1) for ii,jj in enumerate(j) if jj=='N']
print(list1)
輸出:
[[0, 0.21], [-1, 6.6], [0, 34.68]]
我想我已經找到了一種方法來處理任何維度的數組,即使數組的元素並不都具有相同的維度,例如:
array=[
[
['N',2],
[3,'N']
],
[
[5,'N'],
7
],
]
首先,定義一個函數來檢查一個變量是否是可迭代的,就像在 Python 中一樣,我如何確定一個對象是否是可迭代的? :
def iterable(obj):
try:
iter(obj)
except Exception:
return False
else:
return True
然后,使用以下遞歸函數將“N”替換為 0:
def remove_N(array):
"Identify if we are on the base case - scalar number or string"
scalar=not iterable(array) or type(array)==str #Note that strings are iterable.
"BASE CASE - replace "N" with 0 or keep the original value"
if scalar:
if array=='N':
y=0
else:
y=array
"RECURSIVE CASE - if we still have an array, run this function for each element of the array"
else:
y=[remove_N(i) for i in array]
"Return"
return y
示例輸入的輸出:
print(array)
print(remove_N(array))
產量:
[[['N', 2], [3, 'N']], [[5, 'N'], 7]]
[[[0, 2], [3, 0]], [[5, 0], 7]]
你怎么看?
這應該適用於多維列表
orig = [1, 2, ['N', 'b', 1.2], 3, 4)
def replace_items(l, a='N', b=0):
for i, item in enumerate(l):
if (type(l[i]) == type(l)):
l[i] = replace_items(l[i], a=a, b=b)
else:
if l[i] == a:
l[i] = b
return l
new = replace_items(orig, a='N', b=0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.