10

2 つの Python リストがあります。

a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]

b = ['the', 'when', 'send', 'we', 'us']

b の要素に類似する a のすべての要素を除外する必要があります。この場合のように、私は取得する必要があります:

c = [('why', 4), ('throw', 9), ('you', 1)]

最も効果的な方法は何ですか?

4

7 に答える 7

11

リスト内包表記が機能します。

a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]
b = ['the', 'when', 'send', 'we', 'us']
filtered = [i for i in a if not i[0] in b]

>>>print(filtered)
[('why', 4), ('throw', 9), ('you', 1)]
于 2013-02-23T09:30:49.137 に答える
5

リスト内包表記が機能するはずです。

c = [item for item in a if item[0] not in b]

または、辞書の理解を使用して:

d = dict(a)
c = {key: value for key in d.iteritems() if key not in b}
于 2013-02-23T09:28:40.310 に答える
2

これは でタグ付けされているため、リスト内包表記に対してベンチマークnumpyを使用した numpy ソリューションを次に示します。numpy.in1d

In [1]: a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]

In [2]: b = ['the', 'when', 'send', 'we', 'us']

In [3]: a_ar = np.array(a, dtype=[('string','|S5'), ('number',float)])

In [4]: b_ar = np.array(b)

In [5]: %timeit filtered = [i for i in a if not i[0] in b]
1000000 loops, best of 3: 778 ns per loop

In [6]: %timeit filtered = a_ar[-np.in1d(a_ar['string'], b_ar)]
10000 loops, best of 3: 31.4 us per loop

したがって、5 レコードの場合、リストの理解はより高速です。

ただし、大規模なデータセットの場合、numpy ソリューションはリスト内包表記の 2 倍高速です。

In [7]: a = a * 1000

In [8]: a_ar = np.array(a, dtype=[('string','|S5'), ('number',float)])

In [9]: %timeit filtered = [i for i in a if not i[0] in b]
1000 loops, best of 3: 647 us per loop

In [10]: %timeit filtered = a_ar[-np.in1d(a_ar['string'], b_ar)]
1000 loops, best of 3: 302 us per loop
于 2013-02-24T10:37:49.277 に答える
2

inは素晴らしいですが、少なくとも にはセットを使用する必要がありますb。numpy を使用している場合はnp.in1d、もちろん試すこともできますが、より高速であるかどうかに関係なく、おそらく試してみてください。

# ruthless copy, but use the set...
b = set(b)
filtered = [i for i in a if not i[0] in b]

# with numpy (note if you create the array like this, you must already put
# the maximum string length, here 10), otherwise, just use an object array.
# its slower (likely not worth it), but safe.
a = np.array(a, dtype=[('key', 's10'), ('val', int)])
b = np.asarray(b)

mask = ~np.in1d(a['key'], b)
filtered = a[mask]

セットには、differenceおそらくここではあまり役に立たないメソッドなどもありますが、一般的には役に立ちます。

于 2013-02-23T11:11:48.747 に答える
0

これを試して :

a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]

b = ['the', 'when', 'send', 'we', 'us']

c=[]

for x in a:
    if x[0] not in b:
        c.append(x)
print c

デモ: http://ideone.com/zW7mzY

于 2013-02-23T09:30:42.093 に答える
-1

フィルタを使用:

c = filter(lambda (x, y): False if x in b else True, a)
于 2013-02-23T09:33:23.707 に答える