如何将字符串中的数字重复n次?

I have this string (61,62,63,64) and i want to tranform the string into (61,61,62,62,62,62,63,64).

我想将字符串中的数字重复n次,我想重复61次,重复61次,我想重复四次,重复62次,我该如何编码将字符串中的数字重复n次的东西?

Can you possible do something like have annother string that tells the computer how many times to duplicate each number? (61, 62, 63, 64,) (2,4,1,1)

评论
  • isunt
    isunt 回复

    这是一个可能的解决方案:

    s = "(61,62,63,64)"
    rep = (2,4,1,1)
    
    # convert the string to a tuple
    t = eval(s)
    # compute the result as a tuple
    result = tuple(x for i, x in enumerate(t) for _ in range(rep[i]))
    # convert the result into a string
    result = str(result)
    

    如果您想要更紧凑的东西:

    s = "(61,62,63,64)"
    rep = (2,4,1,1)
    
    result = str(tuple(x for i, x in enumerate(eval(s)) for _ in range(rep[i])))
    

    Be careful with using eval!! Check question for more info.