これが私の最初の質問です。質問は簡単です-
# this removes the top list from the list of lists
triangle = [
[3, 0, 0],
[2, 0, 0],
[1, 0, 0]]
del triangle[0]
同様に簡単に「列」を削除する方法が必要です。もちろん、forループを使用してこれを行うことはできますが、同等のものはありますか
del triangle[0]
ありがとうございました
これが私の最初の質問です。質問は簡単です-
# this removes the top list from the list of lists
triangle = [
[3, 0, 0],
[2, 0, 0],
[1, 0, 0]]
del triangle[0]
同様に簡単に「列」を削除する方法が必要です。もちろん、forループを使用してこれを行うことはできますが、同等のものはありますか
del triangle[0]
ありがとうございました
リスト全体をコピーせずにこれを実行したい場合は、次のようになります。
all(map(lambda x: x.pop(which_column), triangle))
編集。はい、列に0がある場合は機能しません。他のアキュムレータ関数を使用するだけです。
sum(map(lambda x: x.pop(which_column), triangle))
map
イテレータアキュムレータではないPython2の場合、次のようになります。
map(lambda x: x.pop(1), triangle)
副作用として、これはあなたが使用するかもしれない削除された列を返します
deleted_column = list(map(lambda x: x.pop(which_column), triangle))
(Python 2の場合list()ラッパーは必要ありません)
短い形式は
sum(i.pop(which_column) for i in triangle)
また
deleted_column = [i.pop(which_column) for i in triangle]
「forループなし」と見なされるかどうかはわかりませんが
PS公式のPythonドキュメントでは、次のように0-lenqthdequeを使用してイテレータを使用します。
collections.deque(map(lambda x: x.pop(which_column), triangle), maxlen=0)
sum()よりも優れているかどうかはわかりませんが、数値以外のデータには使用できます
1つの方法は、zip()を使用して行列を転置し、ターゲット行を削除してから、zipで戻すことです。
>>> def delcolumn(mat, i):
m = zip(*mat)
del m[i]
return zip(*m)
>>> triangle = delcolumn(triangle, 1)
>>> pprint(triangle, width=20)
[(3, 0),
(2, 0),
(1, 0)]
>>> def delcolumn(mat, i):
return [row[:i] + row[i+1:] for row in mat]
>>> triangle = delcolumn(triangle, 1)
>>> pprint(triangle, width=20)
[(3, 0),
(2, 0),
(1, 0)]
最後のテクニックは、 delを使用してマトリックスをインプレースで変更することです。
>>> def delcolumn(mat, i):
for row in mat:
del row[i]