从多个嵌套的列表中更新一个项目

问题描述 投票:0回答:2

我有一个由多个列表组成的列表,我需要能够更新所有列表中出现的最大值,使其变为0。例如,对于这个列表,我想更新最大值,即6为0。那么,我怎样才能同时更新这两个位置呢?

g.graph = [[0, 2, 0, 6, 0],
           [2, 0, 3, 0, 5],
           [0, 3, 0, 0, 0],
           [6, 0, 0, 0, 0],
           [0, 5, 0, 0, 0]]
python
2个回答
2
投票

这可以满足你的要求,但这取决于你所说的 "删除 "是什么意思。

graph = [[0, 2, 0, 6, 0],
         [2, 0, 3, 0, 5],
         [0, 3, 0, 0, 0],
         [6, 0, 0, 0, 0],
         [0, 5, 0, 0, 0]]


def del_max(g):
    m = max(max(row) for row in g)
    return [[x if x != m else None for x in xs] for xs in g]


print(del_max(graph))

你不可能事先知道最大值是什么 所以函数会找到所有行的最大值 然后返回输入数组,其中只有不属于最大值的值。


2
投票

首先你得从这些列表中知道最大值是多少,然后你就可以删除所有出现的值。

这段代码可以解决你的问题。

graph = [[0, 2, 0, 6, 0],
        [2, 0, 3, 0, 5],
        [0, 3, 0, 0, 0],
        [6, 0, 0, 0, 0],
        [0, 5, 0, 0, 0]]

max_val = 0

for lst in graph:
    for item in lst:
        if item > max_val:
            max_val = item

for lst in graph:
    for item in lst:
        if item == max_val:
            lst.remove(item)

print(str(graph))

2
投票

你可以这样做

def update(list_, value):
    try:
        index = list_.index(value)
        list_.[index] = 0
    except ValueError:
        pass

value_to_update = max([i for l in g.graph for i in l])    # Flattening the g.graph list to find the maximum value
list(map(lambda x: update(x, value_to_update), g.graph))    # Calling list() because it needs to run over the map, which is lazy

这段代码实际上更新了原来的值 g.graph 列表,而不是创建一个新的列表。


1
投票

另一种方法,如果你有兴趣使用 itertools.chain 扁平化列表并获得最大值

from itertools import chain
[[0 if j == max(chain(*graph)) else j for j in i] for i in graph]

输出。

[[0, 2, 0, 0, 0],
 [2, 0, 3, 0, 5],
 [0, 3, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 5, 0, 0, 0]]

0
投票
Use remove method.
    list.remove(x)

其中list是你的列表名称,x是需要删除的内容。

© www.soinside.com 2019 - 2024. All rights reserved.