![](/img/trans.png)
[英]Python: Removing an integer in a list within a list is removing the integer on all sublists lists
[英]Replace string by integer in sublists (all ocurrences) - python
這是帶有子列表的可能列表的示例:
rows = [[1, 1, 'x'], [1, 'x', 1], [1, 1, 'x'], [1, 'x', 1], ['x', 1, 1], ['x', 1, 1]]
我正在尋找一種有效的方法來將子列表中的 'x' 替換為 0 或 1。 子列表沒有固定的大小或數量。 我的意思是,它可能是這樣的列表:
[(1, 1, 'x', 'x'), (1, 1, 'x', 'x'), (1, 'x', 1, 'x'), (1, 'x', 'x', 1)]
我試過這個:
for row in rows:
for pos in row:
if pos == 'x':
pos.replace('x','0')
即使知道我需要“0”作為 integer,也只是為了打印 output。 但是行保持'x'不變。
有什么建議么?
您可以只使用list
理解並檢查值並替換它,
>> rows = [[1, 1, 'x'], [1, 'x', 1], [1, 1, 'x'], [1, 'x', 1], ['x', 1, 1], ['x', 1, 1]]
>>> [[0 if y == 'x' else y for y in x] for x in rows] # replace `x` with 0
[[1, 1, 0], [1, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1], [0, 1, 1]]
>>> another = [(1, 1, 'x', 'x'), (1, 1, 'x', 'x'), (1, 'x', 1, 'x'), (1, 'x', 'x', 1)]
>>> [[5 if y == 'x' else y for y in x] for x in another] # replace `x` with 5
[[1, 1, 5, 5], [1, 1, 5, 5], [1, 5, 1, 5], [1, 5, 5, 1]]
試試這個代碼:
rows = [[1, 1, 'x'], [1, 'x', 1], [1, 1, 'x'], [1, 'x', 1], ['x', 1, 1], ['x', 1, 1]]
temp_dic = {'x':0}
modified_list = map(
lambda sub_list: sub_list if 'x' not in sub_list else [temp_dic.get(n, n) for n in sub_list],
rows)
print(list(modified_list))
Output:
[[1, 1, 0], [1, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1], [0, 1, 1]]
基本上,我們正在遍歷子列表並檢查鍵 (x) 是否存在值 (0)。 如果是,請更換它,否則,請保留密鑰。
dic.get(n, n)
如果存在則返回 value(0) 或者它只是返回鍵(例如我們的例子中的數字)。 這樣我們只替換“x”而不是數字。
rows = [[1, 1, 'x'], [1, 'x', 1], [1, 1, 'x'], [1, 'x', 1], ['x', 1, 1], ['x', 1, 1]]
for r in rows:
for i, pos in enumerate(r):
if pos == 'x':
r[i] = 0
print(rows)
#output replace x with 0: [[1, 1, 0], [1, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1], [0, 1, 1]]
#output replace x with 99: [[1, 1, 99], [1, 99, 1], [1, 1, 99], [1, 99, 1], [99, 1, 1], [99, 1, 1]]
這對我來說在 Python 3.7.4 上效果很好。 干杯和好運!
如果您仍想使用替換方法,則需要在替換字符串后將 append 值添加到新列表中:
rows=[(1, 1, 'x', 'x'), (1, 1, 'x', 'x'), (1, 'x', 1, 'x'), (1, 'x', 'x', 1)]
new_list=[]
for row in rows:
sublist=[]
for pos in row:
if pos == 'x':
pos=pos.replace('x','0')
sublist.append(pos)
new_list.append(sublist)
print(new_list)
# [[1, 1, '0', '0'], [1, 1, '0', '0'], [1, '0', 1, '0'], [1, '0', '0', 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.