2017-11-07 4 views
0

「で始まり」に基づいて:私は要素がベースの両方のリストに存在しているかどうかを確認したいPythonの3 - 、二つのリストを比較すると、エルがリストにあるかどうかを見つけ、私は二つのリスト持っている

items_on_queue = ['The rose is red and blue', 'The sun is yellow and round'] 
things_to_tweet = ['The rose is red','The sun is yellow','Playmobil is a toy'] 

をFEW CHARACTERS BEGINNINGに始まり、一致が見つかった場合はthings_to_tweetから要素を削除します。

最終出力は= things_to_tweetしなければならない[「プレイモービルのおもちゃです」]

私はこれを行うことができますどのように任意のアイデア? ありがとうございました

PS /私は試しましたが、それぞれのelがすべてのリストで異なっているため、比較を行うことはできません。たとえ開始しても、Pythonでは同じではないと見なされるからです。 ループ内でループを試しましたが、同じ方法で文字列が始まる場合にのみ、ある要素を別のリストのすべての要素と比較する方法はわかりません。 私は他のSOスレッドもチェックしましたが、要素がまったく同じ場合はリスト間の比較を参照するように見えますが、これは私が必要としないものです。

答えて

1

を使用することができ、私はヘルパー関数を利用するだろう(私はそれを命名is_prefix_of_any )。この機能がなければ、2つのネストされたループがあり、不必要に混乱することになります。文字列が別の文字列の接頭辞かどうかを確認するには、str.startswith関数を使用します。

また、反復処理中のリストから削除すると、予期しない結果が生じることがあるので、things_to_tweetから文字列を削除する代わりに、新しいリストを作成することを選択しました。

# define a helper function that checks if any string in a list 
# starts with another string 
# we will use this to check if any string in items_on_queue starts 
# with a string from things_to_tweet 
def is_prefix_of_any(prefix, strings): 
    for string in strings: 
     if string.startswith(prefix): 
      return True 
    return False 

# build a new list containing only the strings we want 
things = [] 
for thing in things_to_tweet: 
    if not is_prefix_of_any(thing, items_on_queue): 
     things.append(thing) 

print(things) # output: ['Playmobil is a toy'] 

ベテランはこれよりはるかに少ないコードでこれを実行しますが、これは理解しやすくなります。

2

文字列startswith(..)と条件

[s for s in things_to_tweet if not any(i.startswith(s) for i in items_on_queue)] 
#Output: 
#['Playmobil is a toy'] 
+0

@COLDSPEED - 修正ありがとうございました – Transhuman

-1

あなたはシンプルで読みやすいものを維持するにはPythonでstartswithhttps://www.tutorialspoint.com/python/string_startswith.htm

items_on_queue = ['The rose is red and blue', 'The sun is yellow and round'] 
    things_to_tweet = ['The rose is red','The sun is yellow','Playmobil is a toy'] 
    data = [] 

    for thing in things_to_tweet: 
     if not [item for item in items_on_queue if thing == item[:len(thing)]]: 
      data.append(thing) 
    print(data) 

    # or 
    data = [] 

    for thing in things_to_tweet: 
     if not [item for item in items_on_queue if item.startswith(thing)]: 
      data.append(thing) 


    print(data) 
+0

私はすでにそれを試みましたが、どちらもうまくいかなかったのです。私はそれをいかに正確に適用するかわからないと思う。どのようにして正確にやるの?私はそれをしようとするより多くの時間を無駄にするよりも、そのことからもっと学ぶだろうと思う。私はすでにこの周り2hだった。 – skeitel

関連する問題