6

我正在尝试输出字符串的旋转版本。我取了一个字符串 ,z="string"并从中创建了一个双端队列y=collections.deque(z) (deque(['S','t','r','i','n','g']), 并使用 rotate 方法对其进行了旋转。如何将我旋转回的双端队列对象“转换”回字符串?

4

7 回答 7

6

回答您的问题:由于 deque 是一个序列,您通常可以使用str.join从该集合的有序元素中形成一个字符串。更广泛地适用于任何可迭代str.join的Python ,以从一个一个连接在一起的元素中形成一个字符串。

但是,建议,而不是双端队列和旋转和连接,您还可以在字符串本身上连接切片以形成一个新字符串:

>>> z="string"
>>> rot=3
>>> z[rot:]+z[:rot]
'ingstr'

这两种方式都有效:

>>> rz=z[rot:]+z[:rot]
>>> rz
'ingstr'
>>> rz[-rot:]+rz[:-rot]
'string'

除了更容易阅读(恕我直言)之外,它还变得更快:

from __future__ import print_function  #same code for Py2 Py3
import timeit
import collections

z='string'*10
def f1(tgt,rot=3):
    return tgt[rot:]+tgt[:rot]

def f2(tgt,rot=3):
    y=collections.deque(tgt)
    y.rotate(rot)
    return ''.join(y)

print(f1(z)==f2(z))    # Make sure they produce the same result
t1=timeit.timeit("f1(z)", setup="from __main__ import f1,z")
t2=timeit.timeit("f2(z)", setup="from __main__ import f2,z")    
print('f1: {:.2f} secs\nf2: {:.2f} secs\n faster is {:.2f}% faster.\n'.format(
           t1,t2,(max(t1,t2)/min(t1,t2)-1)*100.0)) 

印刷:

True
f1: 0.32 secs
f2: 5.02 secs
 faster is 1474.49% faster.
于 2013-07-25T21:40:19.913 回答
5

Just use str.join() method:

>>> y.rotate(3)
>>> y
deque(['i', 'n', 'g', 's', 't', 'r'])
>>> 
>>> ''.join(y)
'ingstr'
于 2013-07-25T21:38:44.337 回答
3

Just concatenate the characters in the string:

''.join(y)
于 2013-07-25T21:38:40.307 回答
2

Using ''.join(y) should do the trick.

于 2013-07-25T21:38:44.403 回答
2

您可以使用字符串连接方法

''.join(y)

In [44]: import collections
In [45]: z = "string"
In [46]: y = collections.deque(z)
In [47]: ''.join(y) 
Out[47]: 'string'
于 2013-07-25T21:38:20.450 回答
1

A good way is to use the join method on the string.

''.join(y)
于 2013-07-25T21:39:23.127 回答
1

You can use join():

''.join(y)
于 2013-07-25T21:39:35.323 回答