2013-10-05 2 views
0

저는 초보 프로그래머입니다. 목록에서 숫자를 추출하고 정수로 다시 변환하는 데 도움이 필요합니다. 이 프로그램은 숫자 입력 (예 : 305.67)을 사용하여 305와 67로 나눕니다. 미완성 부분을 나타내는 코드가 첨부됩니다. 어떤 도움을 주셔서 감사합니다, 감사합니다!초급 파이썬 : 정수로 목록 추출

def getDollarFormatText(dolAndCent): 

    separateDolCent = str(dolAndCent).rsplit('.',1) 

    return separateDolCent 
+1

당신이 부동의 분수와 합리적인 부품을 얻기 위해 시도하는 경우 ,'modf'를 사용하십시오 – Anycorn

답변

3

너무 가까이 있습니다!

def getDollarFormatText(dolAndCent): 

    separateDolCent = [int(x) for x in str(dolAndCent).split('.')] 

    return separateDolCent 

나는 [INT (x)에 대한 X dolAndCent.split에 ('.')]는 list comprehension (지능형리스트를 만들어 이루어 파이썬에서 매우 일반적인 관용구하고 한 번 매우 강력했다 무엇 그들에게 익숙해 지십시오). 본질적으로, 그것은 당신의 문자열을 '.' (이전과 마찬가지로), 각 요소 ('.'앞뒤에있는 부분)를 반복하는 작은 루프를 만듭니다. 각각의 경우에 대해 int 인 정수로 변환됩니다. 기능.

rsplitsplit으로 변경했습니다. 문자열의 어느 쪽이 나왔는지는 중요하지 않으므로 1이 하나뿐이므로 '01'이 (가) 삭제되었습니다. 어쨌든. 내가 using_underscorescamelCase에서 변수를 변경하는 방법

def get_dollar_format_text(dol_and_cent): 
    '''Returns the dollar and cents part of a money amount as 
    a two element list of integers, where the first element is 
    dollars and the second is cents. 
    ''' 
    return [int(x) for x in str(dol_and_cent).split('.')] 

주의 사항 : 보조 노트로


separateDolCent 변수를 만들 이유가 없다. 이것은 함수와 변수 이름을 위해 파이썬 커뮤니티에서 선호됩니다. 또한 문서화 문자열을 사용하여 함수에 몇 가지 문서를 추가했습니다. 당신이 2, 3.4 또는 345.4311 같은 번호를 처리해야하는 경우


, 당신은 당신의 코드에 다음과 같은 편집을 할 수 있습니다 :

def get_dollar_format_text(dol_and_cent): 
    '''Returns the dollar and cents part of a money amount as 
    a two element list of integers, where the first element is 
    dollars and the second is cents. 
    ''' 
    return [int(x) for x in '{0:.2f}'.format(dol_and_cent).split('.')] 

무엇이하는 일은 두 개의 십진수로 포맷 할 수 강제입니다 22.00이되고, 3.4은 이되고, 345.4311345.43이됩니다. 이렇게하면 항상 두 개의 소수로 센트를 얻습니다.

+0

Wonderful, 도와 주셔서 감사합니다! 그것은 효과가있다! –

+0

@Jr. 정수형 금액 또는 분수 센트의 경우를 처리하기 위해 내 대답을 약간 편집했습니다. – SethMMorton

2

당신은 거의 다 :

def getDollarFormatText(dolAndCent): 

    separateDolCent = map(int,str(dolAndCent).rsplit('.',1)) 

    return separateDolCent 

어떻게 새로운 변수로 각 정수를 저장할 수 있나요? 이 인쇄됩니다

def getDollarFormatText(dolAndCent): 

     a,b = map(int,str(dolAndCent).rsplit('.',1)) 

     print a 
     print b 

getDollarFormatText("5.70") 

:

불과 2 개 바르 (. 예를 들어 ab)로 추출

5 
70 
+0

어쨌든, 각 정수를 새로운 변수에 저장할 수있는 방법을 알고 계신가요? –

+0

도움 주셔서 감사합니다. –