너무 가까이 있습니다!
def getDollarFormatText(dolAndCent):
separateDolCent = [int(x) for x in str(dolAndCent).split('.')]
return separateDolCent
나는 [INT (x)에 대한 X dolAndCent.split에 ('.')]는 list comprehension (지능형리스트를 만들어 이루어 파이썬에서 매우 일반적인 관용구하고 한 번 매우 강력했다 무엇 그들에게 익숙해 지십시오). 본질적으로, 그것은 당신의 문자열을 '.' (이전과 마찬가지로), 각 요소 ('.'앞뒤에있는 부분)를 반복하는 작은 루프를 만듭니다. 각각의 경우에 대해 int
인 정수로 변환됩니다. 기능.
rsplit
을 split
으로 변경했습니다. 문자열의 어느 쪽이 나왔는지는 중요하지 않으므로 1
이 하나뿐이므로 '01'이 (가) 삭제되었습니다. 어쨌든. 내가 using_underscores
에 camelCase
에서 변수를 변경하는 방법
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('.')]
무엇이하는 일은 두 개의 십진수로 포맷 할 수 강제입니다 2
은 2.00
이되고, 3.4
은 이되고, 345.4311
은 345.43
이됩니다. 이렇게하면 항상 두 개의 소수로 센트를 얻습니다.
당신이 부동의 분수와 합리적인 부품을 얻기 위해 시도하는 경우 ,'modf'를 사용하십시오 – Anycorn