ã(ruby|javascript)ã§str.join(array)ãpythonã§list.join(str)ãhttp://blog.livedoor.jp/dankogai/archives/51226075.html
ããã§ã¯listãç¶æ¿ããListã¯ã©ã¹ããããã¦ãããã«joinã¡ã½ããã追å ãã¦ããããlistã«ç´ã«ã¡ã½ãã追å ããæ¹æ³ã¯ãªãã®ã ããã....
å¤åã§ããªãã
Pythonã¯Perl,Rubyã«æ¯ã¹ã¦ãä¸ã®æ¹ã¯åããããæããããã ãã©ãä¸ã®æ¹ã¯å
ãã
Unicodeã®ãã¨ã¾ã§èæ ®ã«å ¥ãã¦å®è£ ããããã«ãå®è£ ãããã¶ãã¨æ³¥èããã®ã«ãªã£ã¦ããã
join ããããã®ãä¸ç¨®é¡ã§ã¯ãªãã¨ããã®ãã join ã list ã®ã¡ã½ããã§ãªãçç±ã®ä¸ã¤ã ãããã
str()ã¯Unicodeãé£ãã¨ä¾å¤ããåãã«ãªããããã§ãã¦"dankogai" + u"å°é£¼å¼¾"ã¯u"dankogaiå°é£¼å¼¾"ã«ãªã£ã¦ãããããã"+".join("dankogai" + u"å°é£¼å¼¾")ãåé¡ãªãu"dankogaiå°é£¼å¼¾"ã«ãªã£ã¦ãããã
ããã¯ãPythonåå¿è
ã«åã£ã¦ã¯ç½ ã ã(ãªã®ã§py3kã§ã¯strãæ¤å»ããã)
str 㨠unicode ã®é¢ä¿ã¯ãä¾ãã° int 㨠double ã®ããã«ãunicode å´ã«èªåã§æ ¼ä¸ããããã¨ãããã®ã ããªã®ã§ u"foo" + "bar" ã®çµæ㯠u"foobar" ã«ãªãã
æ ¼ä¸ãã®éãstråã«ã¯asciiæååãå
¥ã£ã¦ãããã®ã¨ã¿ãªãããascii*1ã¨ãã¦ãã³ã¼ãã§ããªãå ´åã¯UnicodeDeocdeErrorãçºçããã
éã«ãstr(u"foo") ã®ããã«æ示çã«æ ¼ä¸ãããéããascii 以å¤ã®æåãå
¥ã£ã¦ããã UnicodeEncodeError ãçºçããã
ãã®ãã¨ãç解ããã°ãåççã§ä¸è²«æ§ãä¿ããã¦ããã®ãå¤ãã®ã§ããããã§ãã¦ããªãã¦æããªããªãã
ãã¦ãRubyã®Array.join ç¸å½ã®ãåæã«ä¸èº«ãæååã«å¤æããjoinã欲ããå ´åã
def join(iterable, sep=''): return sep.join(unicode(x) for x in iterable)
ã§æ®éã¯å åã ããããã ãã !unicodeãæ··ãã£ã¦ãªãå ´åã¯strãããªãã¨ãã !ã¨ããå ´åã¯ã
def join(iterable, sep=''): def s(x): if isinstance(x, basestring): return x return str(x) return sep.join(s(x) for x in iterable)
ã«ãªãããªãæååã += ã§ç¹ãã¦ããã®ã¯ãæååã®é·ãã«æ¯ä¾ããã³ãã¼ã³ã¹ããçºçãã¦è¨ç®éãææª O(n^2) ã«ãªãå¯è½æ§ãããã®ã§ãå§ãã§ããªãã
ã¨ããããã§ããã®ä»¶ã«é¢ãã¦ã¯ããã©ã¡ãããã¢ããã§ã¯ãªãããã©ã¡ããæ©ã¿å¯ããããããã¨ããç¹ã«ããã¦Pythonãè¦å£ãããã®ã¯å¦ããªãã
ä»ã®è¨èªã«å¯¾ãã¦ã®ãæ©ã¿ãããã¯ãPythonãéè¦ãã¦ãã価å¤ã§ã¯ãªããããã
ãããã¯æ§æãããã°Rubyistãåãããããããããªããã©ãPythonã§ã¯å
å
表è¨ã¨withæããããããããã¯æ§æã®å¿
è¦æ§ã¯çç¡ã§ãå¿
è¦ãç¡ãæ©è½ã¯å°å
¥ããªãã
é åã®ä¸å³ãããªãã¿ã§join()ãã
ã«ãã¦ãã
join the array elements with the delimiter
ã«ãã¦ããè¨èã«è¿ãã®ã¯ Ruby ã JavaScript ã®æ¹ã§ã¯ãªããã
åã¯ä¸»èªã®å ¥ãæ¿ããã§ããã¨ãã話ãããã®ã«ãéããªãã£ããããããç´ãã®ãã§ãã£ã¤ãããããã®ããç´ããã£ã¤ãããã¨è¨ãæãããã¨ãåºããã¿ããã«ãä½ã主èªã«ããã¹ãããªãã¦ã®ã¯ä¸»è¦³ã§ãããªãã®ã«ã
é¢æ°ã¨ãã¦ã¯join(delim, list)ããã¡ã½ããã¨ãã¦ã¯array.join(delim)ãè½ã¨ãã©ããã®ããã«æããããã®ã ã....
ãããªã« str.join ãå«ãªã import string; string.join() ãã©ããã
sep.join() ãç´æã«åãã¦ããããã«æãã人ããããå¤ãã¦ããè¤æ°ã®æååã¨è¤æ°ã®iterableãæ£ããæ±ãã«ã¯ã str.join ã¯åççã§ã array.join ã¯åççã§ã¯ãªãã
*1:sitecustomize.py 㧠sys.setdefaultencoding('utf-8') ããããã¨ã§ascii以å¤ã®ã¨ã³ã³ã¼ãã£ã³ã°ãæå®å¯è½