Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 목록 합계(문자열 유형 포함)

<시간/>

이 튜토리얼에서는 목록의 모든 숫자를 더하는 프로그램을 작성할 것입니다. 목록에 문자열의 숫자가 포함될 수 있습니다. 또는 정수 체재. 예를 참조하십시오.

입력

random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]

출력

4051

프로그램을 작성하려면 다음 단계를 따르세요.

  • 목록을 초기화합니다.
  • 3변수 total 초기화 0.
  • 목록을 반복합니다.
  • 요소가 int인 경우 , 그런 다음 총계에 추가합니다. 두 가지 조건을 확인하여.
    • 요소는 int -> 유형을 확인합니다.
    • 요소는 문자열 형식의 숫자가 됩니다. -> isdigit()을 사용하여 확인 방법.
  • 총계 인쇄

예시

# initialzing the list
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
# initializing the variable total
total = 0
# iterating over the list
for element in random_list:
   # checking whether its a number or not
   if isinstance(element, int) or element.isdigit():
      # adding the element to the total
      total += int(element)
# printing the total
print(total)

출력

위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

4051

결론

튜토리얼에서 의문점이 있으면 댓글 섹션에 언급하세요.