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

목록의 대체 요소 합계(Python)

<시간/>

이 기사의 숫자 목록이 주어지면 해당 목록에 있는 대체 요소의 합계를 계산할 것입니다.

목록 슬라이싱 및 범위 사용

매 초마다 범위 함수를 길이 함수와 함께 사용하여 합산할 요소 수를 구합니다.

예시

listA = [13,65,78,13,12,13,65]
# printing original list
print("Given list : " , str(listA))
# With list slicing
res = [sum(listA[i:: 2])
for i in range(len(listA) // (len(listA) // 2))]
   # print result
   print("Sum of alternate elements in the list :\n ",res)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given list : [13, 65, 78, 13, 12, 13, 65]
Sum of alternate elements in the list :
[168, 91]

범위 및 % 포함

백분율 연산자를 사용하여 짝수 및 홀수 위치의 숫자를 구분합니다. 그런 다음 새 빈 목록의 해당 위치에 요소를 추가합니다. 마지막으로 홀수 위치에 있는 요소의 합과 짝수 위치에 있는 요소의 합을 보여주는 목록을 제공합니다.

예시

listA = [13,65,78,13,12,13,65]
# printing original list
print("Given list : " , str(listA))
res = [0, 0]
for i in range(0, len(listA)):
   if(i % 2):
      res[1] += listA[i]
   else :
      res[0] += listA[i]
# print result
print("Sum of alternate elements in the list :\n ",res)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given list : [13, 65, 78, 13, 12, 13, 65]
Sum of alternate elements in the list :
[168, 91]