如果我們想計算特定的字串或整數,我們應該怎么做。就像我想知道我的串列中有多少個 'p' = ['hello world let play ping pong] python 中有沒有我可以使用的運算子或方法?
uj5u.com熱心網友回復:
您可以使用簡單的 for 回圈來完成。
count = 0
test_str = "hello world lets play ping pong"
for i in test_str:
if i == 'p':
count = count 1
或者,如果您愿意,可以執行以下操作
count = test_str.count('p')
uj5u.com熱心網友回復:
由于您沒有提供有效的串列,因此您的串列看起來不太清楚。
但是,假設您的串列如下所示,試試這個 -
l = ['hello','world', 'lets', 'play', 'ping', 'pong']
sum([i.count('p') for i in l])
3
如果它是一個字串而不是一個串列,那么它就更簡單了——
l = ['hello world lets play ping pong']
l[0].count('p')
3
在此處或此處閱讀有關list.count()方法的更多資訊str.count()
uj5u.com熱心網友回復:
如果您有一個帶有字串的串列,您可以使用list[ indexNumber ]迭代字串。喜歡:
count = 0
listOfStrings = ["hello world lets play ping pong"]
for i in listOfStrings[0]:
if i == 'p':
count = count 1
print(count)
輸出:3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/407409.html
標籤:
