以下のコードスニペットがあります
seta = ["apple","orange","grapes","mango", "starfruit"]
setb = ["papaya","mango","jackfruit","grapes","lychee"]
def setOperation(seta, setb):
union = set(seta) | set(setb)
print(list(union))
intersection = set(seta) & set(setb)
print(list(intersection))
difference = set(seta) - set(setb)
print(list(difference))
difference = set(setb) - set(seta)
print(list(difference))
sdifference = set(seta) ^ set(setb)
print(list(sdifference))
print(list(frozenset(set(seta))))
setOperation(seta,setb)
これは、実行するたびに異なる出力を生成します。お気に入り -
['jackfruit', 'apple', 'mango', 'starfruit', 'grapes', 'lychee', 'orange', 'papaya']
['grapes', 'mango']
['orange', 'apple', 'starfruit']
['jackfruit', 'papaya', 'lychee']
['jackfruit', 'apple', 'starfruit', 'lychee', 'papaya', 'orange']
['orange', 'apple', 'grapes', 'mango', 'starfruit']
そして
['grapes', 'mango', 'apple', 'orange', 'starfruit', 'lychee', 'papaya', 'jackfruit']
['grapes', 'mango']
['starfruit', 'apple', 'orange']
['lychee', 'papaya', 'jackfruit']
['apple', 'orange', 'starfruit', 'lychee', 'papaya', 'jackfruit']
['grapes', 'starfruit', 'mango', 'apple', 'orange']
しかし、私は以下のような出力が必要です-
['apple', 'grapes', 'jackfruit', 'lychee', 'mango', 'orange', 'papaya', 'starfruit']
['grapes', 'mango']
['apple', 'orange', 'starfruit']
['jackfruit', 'lychee', 'papaya']
['apple', 'jackfruit', 'lychee', 'orange', 'papaya', 'starfruit']
この順序の変更により、私は1つのコード競争試験に再び失敗します。簡単なことを見逃したり、愚かなことをしたりした場合はお知らせください。辞書式順序で出力したい。TIA
セットは順序付けされていないため、一貫した順序を期待することはできません。期待される出力はソートされた順序であるため、ソートされた和集合/共通部分などを次のように簡単に表示できます。
seta = set(["apple","orange","grapes","mango", "starfruit"])
setb = set(["papaya","mango","jackfruit","grapes","lychee"])
print(sorted(seta | setb)) # Union
print(sorted(seta & setb)) # Intersection
# ... etc ...
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加