web-dev-qa-db-ja.com

pythonで文字列のリストを結合し、各文字列を引用符で囲みます

私が持っている:

words = ['hello', 'world', 'you', 'look', 'Nice']

私が欲しい:

'"hello", "world", "you", "look", "Nice"'

Pythonでこれを行う最も簡単な方法は何ですか?

73
kadrian
>>> words = ['hello', 'world', 'you', 'look', 'Nice']
>>> ', '.join('"{0}"'.format(w) for w in words)
'"hello", "world", "you", "look", "Nice"'
129
jamylak

単一の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
43
marchelbling

これを試すことができます:

str(words)[1:-1]
25
Thykof
>>> ', '.join(['"%s"' % w for w in words])
7
Emmett Butler