5

私が持っているもの

このようなものです

def mymethod():
    return [[1,2,3,4],
            [1,2,3,4],
            [1,2,3,4],
            [1,2,3,4]]

mylist = mymethod()

for _, thing, _, _ in mylist:
    print thing

# this bit is meant to be outside the for loop, 
# I mean it to represent the last value thing was in the for
if thing:
    print thing

私が欲しいもの

私がやりたいのは、ダミー変数を避けることです。これを行うよりスマートな方法はありますか

for thing in mylist:
    print thing[1]

それを新しい変数に割り当てずに、必要なときにいつでも使用するthing[1]必要があり、物事が面倒になるからです。

pythonに新しいので、明らかな何かが欠けている場合は申し訳ありません

4

5 に答える 5

7

ジェネレータ式をハックできます

def mymethod():
    return [[1,2,3,4],
            [1,2,3,4],
            [1,2,3,4],
            [1,2,3,4]]

mylist = mymethod()

for thing in (i[1] for i in mylist):
    print thing

# this bit is meant to be outside the for loop, 
# I mean it to represent the last value thing was in the for
if thing:
    print thing
于 2012-04-13T11:35:36.967 に答える
3

配列の2番目の列を取得する場合は、次のようにリスト内包表記を使用できます。

a = [ [ 1, 2, 3, 4 ],
      [ 5, 6, 7, 8 ],
      [ 9,10,11,12 ],
      [13,14,15,16 ] ]


second_column = [ row[1] for row in a ]
# you get [2, 6, 10, 14]

これを関数でまとめることができます。

def get_column ( array, column_number ):
    try:
        return [row[column_number] for row in array]
    except IndexError:
        print ("Not enough columns!")
        raise # Raise the exception again as we haven't dealt with the issue.

fourth_column = get_column(a,3)
# you get [4, 8, 12, 16]

tenth_column = get_column(a,9)
# You requested the tenth column of a 4-column array, so you get the "not enough columns!" message.

実際には、長方形の数値配列を使用している場合numpyは、数値のリストのリストではなく、配列を使用する必要があります。


または、Lattywareの暗黙の要求により、ジェネレータバージョン:

def column_iterator ( array, column_number ):
    try:
        for row in array:
            yield row[column_number]
    except IndexError:
        print ("Not enough columns!")
        raise

使用法は通常のリストと同じです。

>>> for item in column_iterator(a,1):
...    print(item)
... 
2
6
10
14
>>> 

ジェネレーターの性質は次のようにわかります。

>>> b = column_iterator(a,1)
>>> b.next()
2
>>> b.next()
6
>>> b.next()
10
>>> b.next()
14
于 2012-04-13T11:51:33.833 に答える
2

確かに、itertools.chainスライスはいつ役立つのでしょうか?

for thing in itertools.islice(itertools.chain(*mylist),1,None,len(mylist)):
    print(thing)

Numpy は、列のスライスにも役立ちます。これはnumpyの別の例です

for thing in numpy.array(mylist)[:,1]:
    print(thing)
于 2012-04-13T11:39:07.903 に答える
1

私は明快さと簡潔さについてのDikeiの答えが好きですが、それでも良い選択肢は単純であると信じています。

for sublist in mylist:
    item = sublist[1]
    ...
    do_stuff(item)
    ...
    do_other_stuff(item)
    ...

それは明確なままであり、より簡単に行うために拡張することができ、おそらく最速です。

ここにいくつかの簡単なテストがあります-ループで何もしないことのおかげでそれらがどれほど正確になるかはわかりませんが、おそらくそれらはアイデアを与えます:

python -m timeit -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in mylist:' '    item=thing[1]' '    pass'
1000000 loops, best of 3: 1.25 usec per loop

python -m timeit -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in (i[1] for i in mylist):' '    pass'
100000 loops, best of 3: 2.37 usec per loop

python -m timeit -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in itertools.islice(itertools.chain(*mylist),1,None,len(mylist)):' '    pass'
1000000 loops, best of 3: 2.21 usec per loop

python -m timeit -s "import numpy" -s "mylist = numpy.array([range(1,8) for _ in range(1,8)])" 'for thing in mylist[:,1]:' '    pass' 
1000000 loops, best of 3: 1.7 usec per loop

python -m timeit -s "import numpy" -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in numpy.array(mylist)[:,1]:' '    pass'
10000 loops, best of 3: 63.8 usec per loop

numpyは、一度生成されると高速ですが、1回の操作でオンデマンドで生成するのは非常に遅いことに注意してください。

大きなリストの場合:

python -m timeit -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in mylist:' '    item=thing[1]' '    pass'
100000 loops, best of 3: 16.3 usec per loop

python -m timeit -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in (i[1] for i in mylist):' '    pass'
10000 loops, best of 3: 27 usec per loop

python -m timeit -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in itertools.islice(itertools.chain(*mylist),1,None,len(mylist)):' '    pass'
10000 loops, best of 3: 101 usec per loop

python -m timeit -s "import numpy" -s "mylist = numpy.array([range(1,100) for _ in range(1,100)])" 'for thing in mylist[:,1]:' '    pass'
100000 loops, best of 3: 8.47 usec per loop

python -m timeit -s "import numpy" -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in numpy.array(mylist)[:,1]:' '    pass'
100 loops, best of 3: 3.82 msec per loop

本当に必要な場合を除いて、速度は常に読みやすさの次に来る必要があることを忘れないでください。

于 2012-04-13T11:51:23.697 に答える
1

メソッドitemgetter()を使用してこれを解決できます。

from operator import itemgetter

def mymethod():
    return [[1,2,3,4],
            [1,2,3,4],
            [1,2,3,4],
            [1,2,3,4]]

mylist = mymethod()

row = map(itemgetter(2), mylist)
print("row %s" % row)

thing = row[-1]

# this bit is meant to be outside the for loop, 
# I mean it to represent the last value thing was in the for
if thing:
    print thing

出力は次のとおりです。

row [3, 3, 3, 3]
3
于 2012-04-13T13:03:47.470 に答える