0

このくびれを見てください:

M = [[1,2,3],
     [4,5,6],
     [7,8,9]]

T = [row[1] for row in M]
print(T)

結果は [2, 5, 8] です。

ここで何かを見つけることができました: http://docs.python.org/py3k/tutorial/datastructures.html#nested-list-comprehensions

しかし、「raw」を使用したこのスキームの理解には満足していません。ドキュメントの他のどこでそれについて読むことができるか教えていただけますか?

ところで、なぜ生?コラムらしい?

4

2 に答える 2

2
T = [row[1] for row in M]

これはリスト内包です。リスト内包表記を使用すると、基本的に、他の反復可能オブジェクト(この場合M)を反復処理しながら、その場でリストを作成できます。

上記のコードは多かれ少なかれこれと同じです:

T = []             # create empty list that holds the result
for row in M:      # iterate through all 'rows' in M
    cell = row[1]  # get the second cell of the current row
    T.append(cell) # append the cell to the list

これはすべて1行にまとめられ、もう少し効率的ですが、基本的な考え方は同じです。

Mは行列ですが、選択した内部表現はリストのリストです。または行のリスト。また、マトリックス内の列に直接アクセスすることはできませんが、マトリックスの単一のTを選択する必要があります。したがって、基本的に各行を調べ、関心のある列のセルを取得して、列のセルを使用して新しいリストを作成します(リストは通常​​水平方向に配置されるため、列の転置されたベクトルを厳密に取得します)。T

于 2012-09-27T10:20:53.710 に答える
0

You iterate through the rows and take second element of the row. Then you collect the extracted elements from the rows. It means that you have extracted the column.

Read the list comprehension from the right to the left. It says:

  • Loop through the matrix M to get the row each time (for row in M).
  • Apply the expression to the row to get what you need (here row[1]).
  • Iterate through the constructed results and build the list of them ([...]).

The last point makes it the list comprehension. The thing between the [ and ] is called a generator expression. You can also try:

column = list(row[1] for row in M)

And you get exactly the same. That is because the list() construct a list from any iterable. And the generator expression is such iterable thing. You can also try:

my_set = set(row[1] for row in M)

to get the set of the elements that form the column. The syntactically brief form is:

my_set = {row[1] for row in M} 

and it is called set comprehension. And there can be also a dictionary comprehension like this:

d = { row[1]: True for row in M }

Here rather artificially, the row[1] is used as the key, the True is used as the value.

于 2012-09-27T10:11:10.950 に答える