05 & 06. Python Bascs-Set Type(set)、データ構造の変更

8947 ワード

5. Set Types


5-(1)set(集合)

<<<set>>>
  myset = {"apple", "banana", "cherry"}

繰り返さない、順序なし

  • 複数のデータを集約可能
  • set資料型のコアは要素が
  • を繰り返すことを許さない.
  • データ間に順序がないため、リストや例のようにインデックスやスライド抽出値を使用することはできません.
    A set is a collection which is unordered, unchangeable, and unindexed.
  • Unordered:
    The items in a set do not have a defined order.
    Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
  • Unchangeable:
    Once a set is created, you cannot change its items, but you can remove items and add new items.
  • Duplicates Not Allowed:
    Sets cannot have two items with the same value.thisset = {"apple", "banana", "cherry", "apple", "cherry"} print(thisset) # {'cherry', 'banana', 'apple'}
  • 5-(2)setの宣言方法

    1. my_set = {1, 2, 3}
    2. my_set = set([1, 2])

    5-(3)setの演算

    java = {"유재석", "김태호", "양세형"}
    python = set(["유재석", "박명수"])
    
    ▶︎ 교집합
        print(java & pyhton)
        print(java.intersection(python))
        # {"유재석"}
    
    ▶︎ 합집합
        print(java | python)
        print(java.union(python))
        # {"김태호", "박명수", "유재석", "양세형"}
    
    ▶︎ 차집합
        print(java - python)
        print(java.difference(python))
        # {"김태호", "양세형"}
    
    ▶︎ 세트에 하나의 값 추가
        python.add("김태호")
        print(python)
        # {"박명수", "김태호", "유재석"}
        
    ▶︎ 세트에 여러 값 추가
    	python.update(["김태호", "하하", "노홍철"])
        print(python)
        # {'박명수', '노홍철', '유재석', '김태호', '하하'}
        # **update()함수 괄호 안에 [ ]을 사용해서 값을 묶어줘야함**
    
    ▶︎ 세트에서 값 제거
    	java.remove("김태호")
        print(java)
        # {"양세형", "유재석"}

    6.資料構造の変更


    LIST -> [ ]
    SET -> { }
    TUPLE -> ( )
      menu = {"coffee", "milk", "juice"}
      print(menu, type(menu))
      #{'milk', 'coffee', 'juice'} <class 'set'>
    
      menu = list(menu)
      print(menu, type(menu))
      #['milk', 'coffee', 'juice'] <class 'list'>
    
      menu = tuple(menu)
      print(menu, type(menu))
      #('milk', 'coffee', 'juice') <class 'tuple'>
    
      menu = set(menu)
      print(menu, type(menu))
      #{'milk', 'coffee', 'juice'} <class 'set'>