your programing

파이썬에서 문자열 목록을 결합하고 각 문자열을 따옴표로 묶습니다.

lovepro 2020. 10. 13. 08:20
반응형

파이썬에서 문자열 목록을 결합하고 각 문자열을 따옴표로 묶습니다.


나는있어 :

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"'

업데이트 : 일부 벤치마킹 (2009mbp에서 수행됨) :

>>> 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하는지 확인하기 위해 joinPython 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])

참고 URL : https://stackoverflow.com/questions/12007686/join-a-list-of-strings-in-python-and-wrap-each-string-in-quotation-marks

반응형