私が持っている:
words = ['hello', 'world', 'you', 'look', 'Nice']
私が欲しい:
'"hello", "world", "you", "look", "Nice"'
Pythonでこれを行う最も簡単な方法は何ですか?
>>> words = ['hello', 'world', 'you', 'look', 'Nice']
>>> ', '.join('"{0}"'.format(w) for w in words)
'"hello", "world", "you", "look", "Nice"'
単一のformat
呼び出しを実行することもできます
>>> words = ['hello', 'world', 'you', 'look', 'Nice']
>>> '"{0}"'.format('", "'.join(words))
'"hello", "world", "you", "look", "Nice"'
更新:いくつかのベンチマーク(2009 mbpで実行):
>>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'Nice'] * 100; ', '.join('"{0}"'.format(w) for w in words)""").timeit(1000)
0.32559704780578613
>>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'Nice'] * 100; '"{}"'.format('", "'.join(words))""").timeit(1000)
0.018904924392700195
format
は実際にはかなり高価なようです
更新2:@JCodeのコメントに従って、map
を追加してjoin
が機能することを確認します。Python 2.7.12
>>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'Nice'] * 100; ', '.join('"{0}"'.format(w) for w in words)""").timeit(1000)
0.08646488189697266
>>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'Nice'] * 100; '"{}"'.format('", "'.join(map(str, words)))""").timeit(1000)
0.04855608940124512
>>> timeit.Timer("""words = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * 100; ', '.join('"{0}"'.format(w) for w in words)""").timeit(1000)
0.17348504066467285
>>> timeit.Timer("""words = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * 100; '"{}"'.format('", "'.join(map(str, words)))""").timeit(1000)
0.06372308731079102
これを試すことができます:
str(words)[1:-1]
>>> ', '.join(['"%s"' % w for w in words])