有人知道一种更有效的方式来扩展字符串,例如将fred
扩展为字符串plaintext
的长度-这样fred
会变成fredfredf
-比这个?
# key='fred', msg='plaintext'?
def keypad(key, msg):
while len(key) < len(msg):
key += key
key = key[:len(msg)]
return key
答案 0 :(得分:5)
from itertools import islice, cycle
key = 'fred'
msg = 'plaintext'
print(''.join(islice(cycle(key), len(msg))))
# fredfredf
答案 1 :(得分:3)
不需要导入,创建的东西越少越好。可能比Austins solution更好(不导入,源代码更长):
key='fred'
msg='plaintext'
def keypad(key, msg):
lk = len(key)
lm = len(msg)
return ''.join( [ key[idx%lk] for idx in range(lm) ] )
print(keypad(key,msg))
# fredfredf
利用key
文本与列表(.join()
的模除法无论如何都会在内部将生成器转换为列表-如此一来就可以更快地使用列表了- @奥斯丁的评论)。
优势:
建议阅读:
List vs generator comprehension speed with join function(对于列表vs生成器,速度为join()
)
答案 2 :(得分:2)
key='fred'
msg='plaintext'
key = key*(len(msg)//len(key) + 1)
print(key[:len(msg)])
#fredfredf
或
print((key*(len(msg)//len(key) + 1))[:len(msg)])
答案 3 :(得分:0)
比Austins好的解决方案好,但比您的好:
您的方法效率不高,因为您
最好计算多久一次
key
适合msg
,并仅创建一个结果字符串(减少创建/销毁的字符串的数量),并减小结果字符串的大小。
key='fred'
msg='plaintext'
def keypad(key, msg):
l=len(msg) # store loally so you do not call len twice on it
mult = l//len(key) + 1
return (key*mult)[:l] # overshoots maximally by len(k)-1 characters
print(keypad(key,msg))
为以下项目创建的字符串
:key = "1234"
msg = "1234567890123456789"
我们创建
"12341234" # you, created, thrown away
"1234123412341234" # you, created, thrown away
"12341234123412341234123412341234" # you
"12341234123412341234" # me
答案 4 :(得分:0)
def keypad(key, msg):
wanted = len(msg)
a, b = divmod(wanted, len(key))
return key * a + key[:b]
或
重复一个字符串,直到其长度至少等于您想要的长度。
您可以计算适当的重复次数并将其放在 该乘法运算符的右侧。
然后,您可以使用数组将其修剪为所需的确切长度 切片:
def keypad(key, msg):
length = len(msg)
return (key * (int(length/len(key))+1))[:length]