該代碼似乎沒有替換字串中的非元音字符。
def vowel_one(s):
not_vowel = '0'
vowels = {'a':'1',
'e':'1',
'i':'1',
'o':'1',
'u':'1'}
#dictionary with keys as vowels, and their values as 1
s = s.lower() #changing list to lowercase
vowelsList = list(s)
for index, item in enumerate(vowelsList): #counter, instead of doing i =1, using enumerate
for key, value in vowels.items():
if item == key: #if character in string is equal to key in dictionary
vowelsList[index] = value #at the indexes of such characters, replace them with dictionary key values
if item != key and item != '1':
vowelsList[index] = not_vowel
return ("".join(vowelsList)) #removes brackets and ','
例如,“vowelOne”的結果應該是:01010101 相反我得到:v1w1l1n1 為什么另一個 if 陳述句不起作用?我想如果給定串列(元音串列)中的專案不等于字典(元音)中的任何鍵,那么它應該用“0”替換它。如果我不嵌套 if 陳述句,那么我只會回傳 0。
卡塔鏈接:https ://www.codewars.com/kata/580751a40b5a777a200000a1/
uj5u.com熱心網友回復:
- 如果您的所有值都是
1. - 你不需要兩個
for loops只會增加時間復雜度的東西。 - 您不需要將 轉換
string為list.
這是我的代碼:
def vowel_one(s):
vowels = ['a', 'e','i', 'o', 'u'] # simple list
#dictionary with keys as vowels, and their values as 1
s = s.lower() #changing list to lowercase
for i in s: # Iterating through every value
if i in vowels: # Check if sub-string in vowels
s = s.replace(i, '1')
else: # If not vowel replace with 0
s = s.replace(i, '0')
return s
print(vowel_one("vowelOne"))
編輯:
如果你想省略spaces你可以添加一個elif條件。嘗試:
def vowel_one(s):
vowels = ['a', 'e','i', 'o', 'u'] # simple list
#dictionary with keys as vowels, and their values as 1
s = s.lower() #changing list to lowercase
for i in s: # Iterating through every value
if i in vowels: # Check if sub-string in vowels
s = s.replace(i, '1')
elif not i.isspace(): # If not vowel and space replace with 0
s = s.replace(i, '0')
return s
print(vowel_one("Mudith is my name"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/527662.html
標籤:Python细绳字典
上一篇:容器中不存在java-8-openjdk-amd64
下一篇:如何按值從字典中洗掉鍵
