0
0

Python のリストってやつは...

Last updated at Posted at 2023-12-07

Python のリストについて,残念に思うこと。

sum はできるのに...

リストについて,まともな操作は殆どできない。

my_list = list(range(1, 100001))

sum(), min(), max() ができるのは,信じられないくらい稀有なこと。

sum(my_list)
5000050000

mean(), std() そのほか,できるものがない。

mean(my_list)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[4], line 1
----> 1 mean(my_list)


NameError: name 'mean' is not defined
std(my_list)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[5], line 1
----> 1 std(my_list)


NameError: name 'std' is not defined

結局のところ,numpy とか statistic を使うしかない。

import numpy as np
np.mean(my_list), np.std(my_list)
(50000.5, 28867.513458037913)
import statistics as st
st.mean(my_list), st.stdev(my_list)
(50000.5, 28867.657796687745)

ちなみに,np.std(my_list) と st.stdev(my_list) が違うが,その原因はいつもの ARE.
不偏か不偏ではないかの些細なこと。

np.mean(my_list), np.std(my_list, ddof=1)
(50000.5, 28867.65779668774)
st.mean(my_list), st.pstdev(my_list)
(50000.5, 28867.513458037913)

背後でどんな汚いことをやってもよいので,mean(), var(), std() など主要な統計関数を利用可能にしてほしいなあ。

それができるなら...

一般のベクトル演算もできるようjにしてほしいものだ。

my_list = list(range(1, 6))

以下は,エラーにならないけどリストを n 回繰り返すという,別の動作をする。

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

+ も別の動作をする。

my_list2 = list(range(11, 16))
my_list + my_list2
[1, 2, 3, 4, 5, 11, 12, 13, 14, 15]

片方がスカラーだと + や - や / や ** でもエラーになる。

a = my_list + 2
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[16], line 1
----> 1 a = my_list + 2


TypeError: can only concatenate list (not "int") to list
a = my_list ** 2
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[17], line 1
----> 1 a = my_list ** 2


TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

まあ,それはそれでリストという型に対して指定された動作をする演算子であると割り切ればよいのだが統一性という点ではちょっと残念。

つい最近になって導入された「セイウチ演算子」みたいに,現在の +, * を +++, *** みたいに変更するか(** はべき乗なので)?

でも,numpy.ndarray みたいな動作をするようにしてしまうと(今までのと混乱が生じるというのは別として)「リスト」の存在意義がないか。

リストという型の存在意義はどこにあるのか...
あるんだろうけど。

0
0
0

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
0