9

これを行う簡単な方法を見つけようとしています:

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']

list1 の順序はそのままで、2 つのリストの共通要素を取得したいので、この結果が期待されます。

list3 = ['little','blue']

私は使っている

list3 = list(set(list1)&set(list2))

ただし、これはlist3 = ['blue', 'little']明らかに、 set() は順序を無視するだけです。

4

4 に答える 4

10

あなたはほとんどそこにいlist3ました。list1

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']

list3 = set(list1)&set(list2) # we don't need to list3 to actually be a list

list4 = sorted(list3, key = lambda k : list1.index(k))

結果:

>>> list4
['little', 'blue']
于 2013-08-16T01:48:47.173 に答える
6

リスト内包表記の使用:

>>> list1 = ['little','blue','widget']
>>> list2 = ['there','is','a','little','blue','cup','on','the','table']
>>> s = set(list2)
>>> list3 = [x for x in list1 if x in s]
>>> list3
['little', 'blue']
于 2013-08-16T01:35:31.203 に答える
0

フィルターを使用した実装は次のとおりです。

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']
set2 = set(list2)
f = lambda x:x in set2

list3 = filter(f, list1)
于 2013-08-16T01:35:43.220 に答える
0

これは、特にエレガントではありませんが、あなたの質問に答えます。

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']
list3 = []
for l1 in list1:
    for l2 in list2:
        if l2 == l1:
            list3.append(l2)

print list3  # ['little', 'blue']
于 2013-08-16T01:40:01.827 に答える