需要使用python从输入"str1="<><<>>=<==<"获得以下输出:"<<<<<>>>==="

  • 本文关键字:输出 str1 python python string
  • 更新时间 :
  • 英文 :


我有一个场景,我试图按如下顺序打印输入:

  • 首先需要打印小于符号
  • then大于符号
  • 之后的
  • 等于符号

我只知道下面的方法来获得输出,是否有任何简洁的方法来获得预期的输出与几行代码

我不知道有任何其他方法比下面,如果有任何其他方法解决方案是赞赏

我的代码:

str1='<><<>>=<==<'
c=[]
e=[]
f=[]
d=[]
for a in str1:
if a=="<":
c.append(a)
for i in str1:
if i==">":
e.append(i)
for y in str1:
if y=="=":
f.append(y)
d=c+e+f
print(d)

期望输出:

<<<<<>>>===

您可以使用*运算符来重复一个字符,并结合生成器表达式:

>>> "".join(s*str1.count(s) for s in "<>=")
'<<<<<>>>==='

试试这个:

str1='<><<>>=<==<'
from collections import Counter
dct = Counter(str1)
''.join((s*dct[s]) for s in '<>=')
# '<<<<<>>>==='

你可以数一下<象征,在符号和>

str1 = '<><<>>=<==<'
output = '<'*str1.count('<')+'>'*str1.count('>')+'='*str1.count('=')
print(output) #<<<<<>>>===

还有另一种使用collections.Counter的方法,但它依赖于遇到的字符的顺序:

str1='<><<>>=<==<'
from collections import Counter
print(''.join(Counter(str1).elements()))
# Prints: <<<<<>>>===

最新更新