我有一个充满None
的列表。如何只替换一个元素而不影响其他元素。我知道这是由于python浅拷贝:
>>> a = [[None] * 3] * 3
>>> a
[[None, None, None], [None, None, None], [None, None, None]]
>>> a[0][1] = 2
>>> a
[[None, 2, None], [None, 2, None], [None, 2, None]]
我想:
>>>a[0][1] = 2
[[None, 2, None], [None, None, None], [None, None, None]]
我知道这可以使用列表理解来完成,如:
>>> a = [[None] * 3 for _ in range(3)]
>>> a
[[None, None, None], [None, None, None], [None, None, None]]
>>> a[0][1] = 2
>>> a
[[None, 2, None], [None, None, None], [None, None, None]]
但我想知道是否还有其他办法?还有更多的pythonic?
我需要这样做,因为bokeh
grid
似乎不接受除None
之外的其他任何内容,以便不提供图表。如果你知道一个更好的选择。 (在这种情况下,a[0][1]
将替换为情节)。