2
3

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 5 years have passed since last update.

【python】 累積和を取るときのお話

Last updated at Posted at 2019-06-12

#1.型に注意

itertools.accumulate()で返ってくるのはlist型ではないので、要素をindexで指定できません(多分)

from itertools import accumulate
list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#ng
cumsum_1 = accumulate(list_1)
print("1:",cumsum_1)
print("type:", type(cumsum_1))

print(cumsum_1[1])

結果
1: <itertools.accumulate object at 0x10f8af108> type: <class 'itertools.accumulate'> Traceback (most recent call last): File "test.py", line 9, in <module> print(cumsum_1[1]) TypeError: 'itertools.accumulate' object is not subscriptable

#2.list型にキャストしよう
list型に変更してしまえばこちらのものなので、普通はこうしてしまいます。

#ok
cumsum_2 = list(accumulate(list_1))
print("2:",cumsum_2)
print("type:",type(cumsum_2))

結果
2: [1, 3, 6, 10, 15, 21, 28, 36, 45, 55] type: <class 'list'> cumsum_2[1]: 3

#3.もっと簡単に(これが書きたかっただけ)
こんな書き方も出来ます
","を忘れると死にます

#ok
* cumsum_3, = accumulate(list_1)
print("3:",cumsum_3)
print("type:",type(cumsum_3))

print("cumsum_3[1]:",cumsum_3[1])

結果
3: [1, 3, 6, 10, 15, 21, 28, 36, 45, 55] type: <class 'list'> cumsum_3[1]: 3

#-1.余談
for文で回すときに使うだけだったらlistにしなくても問題はないです

for c in accumulate(list_1):
    print(c,end=", ")

1, 3, 6, 10, 15, 21, 28, 36, 45, 55,

あと、なにか補足や豆知識あったらおしえてくだしあ。

2
3
1

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?