你如果不遍歷字符串中的每個字符,將會得到預期的結果。
我已經評論了你的代碼,所以你可以看到你的腳本和我的區別。
非工作註釋代碼:
def remove_duplicates(string):
#loop through each char in "abcdefghijklmnopqrstuvwxyz" and call it "string"
for string in "abcdefghijklmnopqrstuvwxyz":
#create variable k that holds a set of 1 char because of the loop
k = set(string)
# create a variable x that holds the difference between 1 and 1 = 0
x = len(string) - len(set(string))
#return these values in each iteration
return k, x
print(remove_duplicates("aaabbbccc"))
輸出:
({'a'}, 0)
工作代碼:
def remove_duplicates(string):
#create variable k that holds a set of each unique char present in string
k = set(string)
# create a variable x that holds the difference between 1 and 1 = 0
x = len(string) - len(set(string))
#return these values
return k, x
print(remove_duplicates("aaabbbccc"))
輸出:
({'b', 'c', 'a'}, 6)
P.S:,如果你想你的結果是爲了,你可以改變return k, x
到return sorted(k), x
,但隨後的輸出將是一個列表。
(['a', 'b', 'c'], 6)
編輯:如果你只想如果某些條件得到滿足你的代碼運行 - 例如,僅運行如果字符串沒有任何號碼 - 你可以添加一個if/else語句:
例如代碼:
def remove_duplicates(s):
if not s.isdigit():
k = set(s)
x = len(s) - len(set(s))
return sorted(k), x
else:
msg = "This function only works with strings that doesn't contain any digits.."
return msg
print(remove_duplicates("aaabbbccc"))
print(remove_duplicates("123123122"))
輸出:
(['a', 'b', 'c'], 6)
This function only works with strings that doesn't contain any digits..
好的,我如何將字符串限制爲僅用於運行代碼的字母表。就像你的代碼也會運行「22233377」一樣。這就是我想要做的,「在TTT中爲xx」運行 – wapadunk
您必須添加一個「if/else」子句。我已經更新了我的答案,請看一看。 –
幫助!我一直在試圖將這個輸出(['a','b','c'],6)轉換爲(「abc」,6)。 – wapadunk