0
1

More than 3 years have passed since last update.

list.split("文字")みたいなことをやりたい場合

Posted at

 はじめに

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'] ←意図した出力
0
1
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
0
1