mar*_*632 0 python tuples python-3.x
我是游程编码的新手,需要帮助.我已经获得了一系列整数的行程字符串,后跟包含字母/字符的字符.
例如,我有一个字符串:
1-4c8k2)
Run Code Online (Sandbox Code Playgroud)
我需要将其转换为:
-cccckkkkkkkk))
Run Code Online (Sandbox Code Playgroud)
我所做的是将游程长度字符串转换为元组列表:
[('1','-'),('4','c'),('8','k'),('2','c')]
并尝试创建一个将其转换为字符串的函数但是我得到一个
TypeError:不能将序列乘以'str'类型的非int .
def decode(lst):
q = ''
for count, character in lst:
q += count * character
return q
Run Code Online (Sandbox Code Playgroud)
我试图想出一种方法来改善空间复杂性,而不是创建一个新的元组列表等等,试图解决这个TypeError.
我怀疑发生的事情是你忘记将计数转换为ints:
>>> 3 * 'a'
'aaa'
Run Code Online (Sandbox Code Playgroud)
>>> '3' * 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
Run Code Online (Sandbox Code Playgroud)
>>> int('3') * 'a'
'aaa'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |