我有一個場景,我試圖按以下順序列印輸入:
我有一個場景,我試圖按以下順序列印輸入。
- 首先需要列印小于符號 。
- 然后大于符號
- 然后等于符號 。
由于我只知道下面的方法來獲得輸出,是否有任何簡潔的方法來獲得預期的輸出,只需幾行代碼
。我不知道有什么比下面的方法,如果有任何其他的方法,希望能得到解決
。我的代碼:
str1='<><>> =<==<'/span>
c=[]
e=[]
f=[]
d=[]
for a in str1:
if a=="<"/span>:
c.append(a)
for i in str1:
if i==">"/span>:
e.append(i)
for y in str1:
if y=="="/span>:
f.append(y)
d=c e f
print(d)
預期輸出 :
<<<<>>===。
uj5u.com熱心網友回復:
你可以使用*運算子來重復一個字符,結合一個生成器運算式:
>>> "". join(s*str1.count(s) for s in "<>="/span>)
'<<<<>>===')
uj5u.com熱心網友回復:
嘗試一下:
str1='<><>> =<==<'
from collections import Counter
dct = Counter(str1)
''.join((s*dct[s]) for s in '<>=')
# '<<<<>>=='/span>
uj5u.com熱心網友回復:
你可以先用.count()方法計算<符號、>符號和=符號的數量。然后,相應地列印這些符號。
str1 = '<><>>=<'/span>
output = '<'*str1.count('<') '> '*str1. count('> ') '='*str1.count('=')
print(output) #<<<>>==
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/324430.html
標籤:
