如何在Python中将list转换成不带loop和join()的字符串

2024-10-08 18:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个任务,按如下所示对列表进行排序:

Input:  "Sorting1234"
Output: "ginortS1324"

如果不使用join()用于,而则在代码中的任何位置。 经过多次尝试按要求的方式排序后,我成功了,但我无法将其打印为字符串

^{pr2}$

下面是我使用sorted()进行排序的算法:

st=input()
def iseven(x):
if x.isdigit():
    return int(x)+9 if int(x)%2==0 else int(x)
res=sorted(st, key=lambda x: (x.isdigit(), x.isupper(), iseven(x), ord(x) ))
print(res)

请帮我这个忙


Tags: 代码列表inputoutputif排序resint
3条回答

不使用join,持续或暂时:

print(reduce(lambda x,y:x+y, res, ''))

隐式使用循环,但回答了您的问题!在

but I am unable to print it as a string

只需在调用print()时使用*运算符将参数从列表中解压出来,并使用""作为separator

>>> L = ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']
>>> print(*L, sep="")
ginortS1324

您可以使用reduce,它不在禁止列表中。在代码末尾附加以下行:

new_res=reduce( lambda x,y: x+y, res, "")
print(new_res)

相关问题 更多 >

    热门问题