[英]Sublist into String Python
I have a little problem, I have this code and I need to convert the final print to a string, to be able to printthe final results in different lines and change the separator "," to a "+".我有一个小问题,我有这段代码,我需要将最终打印转换为字符串,以便能够在不同的行中打印最终结果并将分隔符“,”更改为“+”。 If someone could help me to fix this I will be grateful:D.
如果有人可以帮助我解决这个问题,我将不胜感激:D。
Thks in advance ^^.提前致谢^^。
Ex.:前任。:
Input: 7
输入:
7
Output: Output:
5 + 2
5 + 1 + 1
2 + 2 + 2 + 1
2 + 2 + 1 + 1 + 1
2 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1
Code:代码:
def change(coins, amount)
res = []
def getchange(end, remain, cur_result):
if end < 0: return
if remain == 0:
res.append(cur_result)
return
if remain >= coins[end]:
getchange(end, remain - coins[end], cur_result + [coins[end]])
getchange(end - 1, remain, cur_result)
getchange(len(coins) - 1, amount, [])
return res
q = int(input("Write your change: "))
st = change([1, 2, 5, 10], q)
print(st)
change your last line code from print(st)
to将您的最后一行代码从
print(st)
更改为
for s in st:
print('+'.join((map(str,s))))
If st
is a list of integers, you can change it to如果
st
是整数列表,则可以将其更改为
print(" + ".join(str(s) for s in st))
Generators and comprehensions are generally preferred to the map
operation.生成器和推导通常优于
map
操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.