0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

inやnot in の書き方

Last updated at Posted at 2023-04-04
<要素> not in <集合>
not (<要素> in <集合>)
式はこんな感じ

a = [1,2,3,4,5]

print(0 not in a)
print(not(0 in a))

#1がリストに存在しているかを判別するif
if 1 in a:
    print("1が入っている!")

# not inの方が可動性が高くpep8にも沿っている
- if not 1 in a:
-   print("1は入っていません")
+ if 1 not in a:
+   print("1は入っていません")


#余談
#リストから該当する文字を含むものを抽出する
a = ["202202","202203"]

b = [i for i in a if i in "202202"]

#文頭に202202を見つける
b = [i for i in a if i.startswith("202202")]

print(b)
#->[202202]

#ただし無駄な文字が入っていた場合
a = ["hoge202202","202203hoge"]

b = [i for i in a if i in "202202"]
#=>[]
# これダメなんですね。inを使えば文字を"含むもの"を抽出してくれると思っていたので、
この場合はあまりinを使う場面ではないかもしれない

b = [i for i in a if i.startswith("202203")]
#=>["202203"]
print(b)

参考:
startwith
https://itsakura.com/python-startswith

0
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?