2013-03-03 5 views
0

안녕하세요 여러분 모두 파이썬 질문이 있습니다.문자열의 각 문자를 한 번만 인쇄하는 방법

주어진 문자열의 각 문자를 한 번만 인쇄하려고합니다. 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'] 

오류없이 ...

+0

당신은 베네 수 설정 데이터 구조에서 적합 http://docs.python.org/2/tutorial/datastructures.html#sets - 당신이해야 할 것보다 더 많이 인쇄하고있는 것처럼 보임 (들여 쓰기 참조) –

+0

'print (sorted (set (sentence_str.lower())))' – jfs

+0

@JFSebastian - 멋지지만 구두점이 여전히 포함되어 있습니다 ... –

답변

2

그냥 확인 그것 :

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

또는 배열 대신 파이썬에서 제공하는 Set 데이터 구조를 사용하십시오. 세트는 중복을 허용하지 않습니다.

aSet = set(letter_str) 
+0

두 번째 예제는'aSet = set (letter_str)'일 수 있습니다 (인쇄를 제외하고 디버깅을 제외하고는 필수적이지는 않습니다) –

+0

@MichaelMauderer 감사합니다. 전체 문자열, 난 문자열 자체가 될 한 요소의 집합을 얻을 것이다. 이렇게 적용된 세트를 몰랐습니다. –

+0

@HunterMcMillen 문자열을 반복 할 때 각각의 문자를 얻을 수 있기 때문에 효과가 있습니다. 어떤 반복 가능한 것을 하나의 세트로 변환 할 수 있기 때문에'set ()'은'set ( entropy

0

는 중요하지 않습니다 인쇄 할 순서가 사용할 수있는 경우 :

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)) 

아니면 정렬 된 순서로 인쇄 할 경우 당신이 그것을 다시 변환 할 수를 나열하고 sort()를 사용하는 그런 다음 인쇄하십시오. 당신이 말할 수

2

사용 itertools ifilter을위한 루프 암시가 있습니다

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']) 
+0

암시 적 집합 이해를 사용하여 조금 더 단순화 할 수 있습니다. 파이썬 2.7 가정. 'a = {i for itertools.ifilter (lambda x : x.isalpha(), sentence_str.lower())}' – Anorov

2

말볼 리오가 올바르게 대답은 가능한 한 단순해야한다고 주장한다. 이를 위해 Python의 set 유형을 사용하여 고유성 문제를 가장 효율적이고 간단한 방식으로 처리합니다.

그러나 그의 대답은 구두점 및 간격을 제거하는 것을 다루지 않습니다. 게다가, 질문에있는 모든 대답과 코드는 매우 비효율적입니다 (badchar_str을 반복하고 원래 문자열에서 바꾸기).

있는 최선 (즉, 가장 간단하고 효율적인뿐만 아니라 관용적 파이썬) 문장의 모든 고유 문자를 찾을 방법은 이것이다 : 당신이 그 (것)들을 정렬하려면

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) 
+0

대단히 감사합니다! –

0

당신은) (제거 중복 문자() 설정 및 분류 사용할 수 있습니다

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)) 
관련 문제