[英]Separate each letter from a text without saving the same letter twice
我想知道如何在不將同一個字母在 python 中保存兩次的情況下,用不同的字母分隔文本。 所以像"hello"
這樣的文本的輸出將是{'h','e',l','o'}
,只計算字母l
一次。
正如評論所說,把你的話放在一個set
以刪除重復項:
>>> set("hello")
set(['h', 'e', 'l', 'o'])
遍歷它(集合沒有順序,所以不要指望它):
>>> h = set("hello")
>>> for c in h:
... print(c)
...
h
e
l
o
測試一個字符是否在其中:
>>> 'e' in h
True
>>> 'x' in h
False
有幾種方法可以做到這一點...
word = set('hello')
或者以下...
letters = []
for letter in "hello":
if letter not in letters:
letters.append(letter)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.