2017-09-08 8 views
3

2つのリストがあります。 1つにはすべてのカテゴリがあり、もう1つはレビューする必要があるカテゴリのみです。私は次のようになります。一つの完全なリスト、持っていると思います一覧の更新と置換の組み合わせ

List_one = ('Maths', 'English', 'Science')

List_two = ('Maths:2', 'Science:4')

List_three = ('Maths:2', 'English', 'Science:4')

に任意の助けいただければ幸いです!

+2

これらのリストは '{'Maths':2、 'Science':4}'のようなものではないはずですか?それはおそらくもっと扱いやすいでしょう。 –

+0

これらはリストではなく、それらは 'タプル 'です – Netwave

+0

grep -r -c -i string * .txtの端末出力を読み込んでいます。出力の各行は変数になります –

答えて

3

置換を実行するときに一定の時間の参照を実行するために中間dictを作成することで、パフォーマンスを向上させることができます。 dict.getを使用して

dict_two = {x.split(':')[0] : x for x in List_two} 

out = [dict_two.get(x, x) for x in List_one] 
print(out) 
['Maths:2', 'English', 'Science:4'] 

、あなたはリストの要素を置き換えることができますし、O(n)時間複雑で、同時にKeyError秒を避けます。

2

Coldspeedは、最もパフォーマンスの高いアプローチを指摘しました。純粋なアプローチは、リスト2に一致するリスト1のアイテムを削除してリスト2を追加するリスト項目を削除する

です。しかし暗黙のanyループのためにパフォーマンスが悪いです。 List_tempの

0
List_one = ('Maths', 'English', 'Science') 
List_two = ('Maths:2', 'Science:4') 
import copy 
List_temp = list(copy.copy(List_one)) #Creating a copy of your original list 

出力:

[ '数学'、 '英語'、 '科学']コードの

#Iterate through each element of List_temp and compare the strings with each element of List_two 

#Have used python's inbuilt substring operator to compare the lists 

for i in List_temp: 
List_three = [] 
for j in range(len(List_two)): 
    if str(i) in str(List_two[j]): 
     y = i 
     List_temp.remove(y) #Remove the elements present in List_two 
List_three = List_two + tuple(List_temp) #Since we cant merge a tuple and list, have converted List_temp to tuple and added them to create a new tuple called List_three 
print(List_three) 

出力:

( '数学:2'、 'Science:4'、 'English')

希望があれば

関連する問題