반응형
파이썬에서 문자열 목록을 결합하고 각 문자열을 따옴표로 묶습니다.
나는있어 :
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
하는지 확인하기 위해 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])
반응형
'your programing' 카테고리의 다른 글
Newtonsoft JSON 역 직렬화 (0) | 2020.10.13 |
---|---|
정수에 대한 나누기와 모듈로를 어떻게 계산할 수 있습니까? (0) | 2020.10.13 |
JPA 주석에 다중 열 제약 조건을 도입하는 방법은 무엇입니까? (0) | 2020.10.13 |
ajax 방식으로 레일 3에 양식 제출 (jQuery 사용) (0) | 2020.10.13 |
자바 getHours (), getMinutes () 및 getSeconds () (0) | 2020.10.13 |