はじめに
pythonのsplit()関数はよく使うが、文字列にしか使えない。
listの時も使いたいと思って調べたが、意外と見つからない。
したがって備忘録がてらコードを書いた。
やりたいこと
文字列に対して行うsplit()をlistに対してもやりたい。
文字列に対してのsplit()の例は
s = "1032"
s.split("0")
# ['1', '32']
具体的には
a = ["1","0","3","2"]
#これはエラー
#a.split("0")
#[["1"],["3","2"]]
みたいなことがしたい。
コード
list_split.py
def list_split(L,moji):
return_L,tmp = [],[]
for val in L:
if val != moji:
tmp.append(val)
elif val == moji:
return_L.append(tmp)
tmp = []
return_L.append(tmp)
return return_L
"""
#this is sample code
if __name__=="__main__":
a = ["1","0","3","2"]
print(list_split(a,"0"))
#[['1'], ['3', '2']]
"""
その他注意事項
最初にlistの要素を結合し文字列にしてからsplit()すれば良いのでは?と思ったが、これはバグる可能性がある。
具体例としては以下のようなケースが挙げられる。
a = ["1","0","3","10","2"]
s = "".join(a)
#'103102'
s.split("0")
#['1', '31', '2'] ←間違い
#['1', '3102'] ←意図した出力