从Python中的给定字符串中删除所有重复项
要从python中的字符串中删除所有重复项,我们需要先将字符串用空格分开,以使每个单词都位于数组中。然后,有多种方法可以删除重复项。
我们可以通过以下方式删除重复项:首先将所有单词都转换为小写,然后对其进行排序,最后仅选择唯一的单词。例如,
示例
sent = "Hi my name is John Doe John Doe is my name"
# Seperate out each word
words = sent.split(" ")
# Convert all words to lowercase
words = map(lambda x:x.lower(), words)
# Sort the words in order
words.sort()
unique = []
total_words = len(words)
i = 0
while i < (total_words - 1):
while i < total_words and words[i] == words[i + 1]:
i += 1
unique.append(words[i])
i += 1
print(unique)输出结果
这将给出输出-
['doe', 'hi', 'john', 'is', 'my']
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿