簡體   English   中英

如何僅將字符串中的每個字母打印一次

[英]How to print each letter in a string only once

大家好,我有一個python問題。

我正在嘗試只將給定字符串中的每個字母打印一次。 如何使用for循環並從a到z排序字母?

這是我所擁有的;

import string

sentence_str = ("No punctuation should be attached to a word in your list, 
                e.g., end.  Not a correct word, but end is.")

letter_str = sentence_str 
letter_str = letter_str.lower()

badchar_str = string.punctuation + string.whitespace

Alist = []


for i in badchar_str:
    letter_str = letter_str.replace(i,'')


letter_str = list(letter_str)
letter_str.sort() 

for i in letter_str:
    Alist.append(i)
    print(Alist))

答案我得到:

['a']
['a', 'a']
['a', 'a', 'a']
['a', 'a', 'a', 'a']
['a', 'a', 'a', 'a', 'a']
['a', 'a', 'a', 'a', 'a', 'b']
['a', 'a', 'a', 'a', 'a', 'b', 'b']
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c']....

我需要:

['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i', 'l', 'n', 'o', 'p', 'r', 's', 't', 'u', 'w', 'y']

沒有錯誤...

只需在附加字母之前檢查字母是否在您的數組中即可:

for i in letter_str:
    if  not(i in Alist):
        Alist.append(i)
    print(Alist))

或者使用Python提供的Set數據結構代替數組。 集不允許重復。

aSet = set(letter_str)

使用itertools ifilter ,您可以說它具有隱式的for循環:

In [20]: a=[i for i in itertools.ifilter(lambda x: x.isalpha(), sentence_str.lower())]

In [21]: set(a)
Out[21]: 
set(['a',
     'c',
     'b',
     'e',
     'd',
     'g',
     'i',
     'h',
     'l',
     'o',
     'n',
     'p',
     's',
     'r',
     'u',
     't',
     'w',
     'y'])

馬爾沃里奧正確地指出,答案應盡可能簡單。 為此,我們使用python的set類型,它以最有效和最簡單的方式處理唯一性問題。

但是,他的答案並不涉及刪除標點符號和空格。 此外,所有答案以及問題中的代碼的執行效率都非常低(通過badchar_str循環並替換為原始字符串)。

在句子中查找所有唯一字母的最佳方法(即最簡單,最有效以及慣用的python)是這樣的:

import string

sentence_str = ("No punctuation should be attached to a word in your list, 
                e.g., end.  Not a correct word, but end is.")

bad_chars = set(string.punctuation + string.whitespace)
unique_letters = set(sentence_str.lower()) - bad_chars

如果要對它們進行排序,只需將最后一行替換為:

unique_letters = sorted(set(sentence_str.lower()) - bad_chars)

如果您要打印的順序無關緊要,則可以使用:

sentence_str = ("No punctuation should be attached to a word in your list, 
                e.g., end.  Not a correct word, but end is.")
badchar_str = string.punctuation + string.whitespace
for i in badchar_str:
    letter_str = letter_str.replace(i,'')
print(set(sentence_str))

或者,如果要按排序順序打印,可以將其轉換回list並使用sort()然后進行打印。

第一原則,克拉麗絲。 簡單。

list(set(sentence_str))

您可以使用set()刪除重復的字符和sorted():

import string

sentence_str = "No punctuation should be attached to a word in your list, e.g., end.  Not a correct word, but end is."

letter_str = sentence_str 
letter_str = letter_str.lower()

badchar_str = string.punctuation + string.whitespace

for i in badchar_str:
    letter_str = letter_str.replace(i,'')

characters = list(letter_str);

print sorted(set(characters))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM