【備忘録】{セット}の基本

python3
あくまで備忘録なんで雑に記録します

① {セット}のメリットは、重複のない集合

空の波括弧{}は辞書型dictと見なされる!

S = {}
S.add(1) #エラー

S = {0}
S.add(1)#{0, 1}

A = [1, 1, 2, 3, 3, 4, 4, 4]
A = set(A)
A = list(A)
print(A)#[1, 2, 3, 4]

②追加と削除

add():要素を追加
discard():要素を削除 存在しない値で非エラー
remove():要素を削除 存在しない値でエラー
pop():ランダム要素を削除し、その値を返す

S = {1, 2, 3}
S.add(4)#{1, 2, 3, 4}
S.discard(1)#{2, 3, 4}
#S.remove(1)#エラー
A = S.pop()#2
print(S)#{3, 4}

③和・積・差・XOR

和:【|】
積:【-】
差:【&】
XOR(排他的論理和):【^】

a = {1, 2, 3}
b = {2, 3, 4}
print(a|b)#{1, 2, 3, 4}
print(a&b)#{2, 3}
print(a-b)#{1}
print(b-a)#{4}
print(a^b)#{1, 4}

④集合の包含とか判定

完全一致:【==】
完全不一致:【isdisjoint】
部分集合:【>=】

a = {0, 1}
b = {1, 2}
c = {2, 3}

#一致?
print(a==b)#False

#互いに素?
print(a.isdisjoint(b))#False
print(a.isdisjoint(c))#True

#含む?
print(a>=b)#False
b.remove(2)
print(a>=b)#True

コメント

"+r+""+h+""+">"}var c,i=n(45),u=n(74),f=n(64),s=n(53),p=n(76),l=n(41),y=(n=n(52),"prototype"),h="script",v=n("IE_PROTO"),g=function(){try{c=new ActiveXObject("htmlfile")}catch(r){}var r;g="undefined"==typeof document||document.domain&&c?function(r){r.write(a("")),r.close();var t=r.parentWindow.Object;return r=null,t}(c):((r=l("iframe")).style.display="none",p.appendChild(r),r.src=String("javascript:"),(r=r.contentWindow.document).open(),r.write(a("document.F=Object")),r.close(),r.F);for(var t=f.length;t--;)delete g[y][f[t]];return g()};s[v]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(o[y]=i(t),n=new o,o[y]=null,n[v]=t):n=g(),e===r?n:u.f(n,e)}},function(r,t,e){var n=e(5),o=e(44),a=e(43),c=e(45),i=e(11),u=e(75);t.f=n&&!o?Object.defineProperties:function(r,t){c(r);for(var e,n=i(t),o=u(t),f=o.length,s=0;s=t||56320!=(64512&i(r,e))))return!1}return!0}})},function(r,t,e){var n=e(91),o=String;r.exports=function(r){if("Symbol"===n(r))throw new TypeError("Cannot convert a Symbol value to a string");return o(r)}},function(r,t,e){var n=e(2),o=e(7),a=e(13),c=e(15),i=e(102),u=(e=e(6),Array),f=a("".charAt),s=a("".charCodeAt),p=a([].join),l="".toWellFormed,y=l&&e((function(){return"1"!==o(l,1)}));n({target:"String",proto:!0,forced:y},{toWellFormed:function(){var r=i(c(this));if(y)return o(l,r);for(var t=r.length,e=u(t),n=0;n
タイトルとURLをコピーしました