LoginSignup
1
0

20240322の日記、Pythonの細かいこと(スコープのこと、foldをpythonっぽく)、PowerShellに色付け

Last updated at Posted at 2024-03-21

Pythonあれこれ

スコープきもちわるい

if ~~~:
    x = 'zzz'
else:
    x = 'aaa'
print(x)

というときにxがちゃんとzzzかaaaのいずれかになるのが気持ちわるい

for i in range(100)
    try:
        x = x + i
    except NameError:
        x = i
print(x)

とすると4950となって気持ち悪い

if文、for文はスコープ用のブロック(?)を作らないのでなんか気持ち悪い
内包表記の中で使っている一時変数みたいなのは外ではアクセスできない

a = [x for x in range(5)]
print(a) # -> [0,1,2,3,4]
print(x) # -> エラーになる

参考:意外とややこしい Python のスコープを理解するためのクイズ14問 #Python - Qiita

foldしたい

こんな感じのこと

ruby
[1,2,3,4,5].reduce(0) {|s,i|, s+i} # -> 15
scala
(1 to 5).toList.reduceLeft{_ + _} // -> 15
haskell
foldl (+) 0 [1,2,3,4,]

二つ方法があって、一つはfunctoolsというモジュールを使う方法、もうひとつは:=という演算子を使う方法

# functools使う
from functools import reduce
a = reduce(lambda a,b: a+b, [1,2,3,4,5], 0)
print(a)  # -> 15

# もう一つ、functooslとoperator
import operator
from functools import reduce
a = reduce (operator.add, [1,2,3,4,5], 0)
print(a)  # -> 15

# :=使う方法
acc = 0
[acc := acc + x for x in [1,2,3,4,5]]
print(acc)  # -> 15

参考: python - What is the 'pythonic' equivalent to the 'fold' function from functional programming? - Stack Overflow

PowerShell

1
0
5

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
1
0