実現したいこと
arr
が int
のみを使ったリストであるということを判定したいです。
以下のコードを書きました。
python
1arr = [13, 22, 35, 41, 59] 2 3if type(arr) is list[int]: 4 print('true') 5else: 6 print('false')
これでは list[int]
の type が types.GenericAlias
なので常に Flase
となってしまうことは理解しています。
やってみたこと
for 文を使って調べることはできますが、できれば list[int]
を使って判定したいです。
どのようにすれば list[int]
を使って list
の要素がすべて int
型であると判定できますか?
stackoverflowでの類似質問に対して for文やイテレータを使っていない以下のような回答がありました
「Check if all elements of a list are of the same type」
https://stackoverflow.com/questions/13252333/check-if-all-elements-of-a-list-are-of-the-same-type
# To check whether all elements in a list are integers
set(map(type, [1,2,3])) == {int}
# To check whether all elements are of the same type
len(set(map(type, [1,2,3]))) == 1
mapやらsetやら使っている時点でfor文を使ったものよりもメリットがあるのかは不明。
ご紹介まで

回答1件
あなたの回答
tips
プレビュー