1

これが私の最初の質問です。質問は簡単です-

# 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]

ありがとうございました

4

2 に答える 2

4

リスト全体をコピーせずにこれを実行したい場合は、次のようになります

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()よりも優れているかどうかはわかりませんが、数値以外のデータには使用できます

于 2012-07-01T08:09:51.443 に答える
3

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]
于 2012-07-01T07:57:40.963 に答える