Prepare > Python > Built-Ins > Zipped!

2023. 9. 26. 20:03HackerRank-Python

 

Zipped! | HackerRank

Compute the average by zipping data.

www.hackerrank.com

 

문제


Task

The National University conducts an examination of N students in X subjects.
Your task is to compute the average scores of each student.

Input Format

The first line contains N and X separated by a space.
The next X lines contains the space separated marks obtained by students in a particular subject.

Output Format

Print the averages of all students on separate lines.

The averages must be correct up to 1 decimal place.

 

=> N명의 학생, X개의 과목에 대해 각 학생들의 시험 평균을 출력하라.

 

 

 

 

코드


N, X = map(int, input().split())

li = []
for i in range(X):
    X_i = [float(x) for x in input().split()]
    li.append(X_i)


for i in list(zip(*li)):
    print(sum(i) / len(i))

 

 

 

 

노트


zip()

튜플로 이뤄진 리스트를 리턴(객체로 리턴인듯..?)

print(zip([1,2,3,4,5,6],'Hacker'))
# [<zip object at 0x7d1bd358e340>]

 

각 튜플들에 대해, n번째 튜플은 각 인수들의 n번째 요소들로 이뤄짐

print(list(zip([1,2,3,4,5,6],'Hacker')))
# [(1, 'H'), (2, 'a'), (3, 'c'), (4, 'k'), (5, 'e'), (6, 'r')]

 

각 인수들은 iterable 객체로, 가장 짧은 길이의 객체 길이 만큼만 zip 튜플이 나옴

print(list(zip([1,2,3,4,5,6],[0,9,8,7,6,5,4,3,2,1])))  # 6개 vs 10개 짜리 객체
# [(1, 0), (2, 9), (3, 8), (4, 7), (5, 6), (6, 5)]  # 6개 짜리 길이

 

예시

A = [1,2,3]
B = [6,5,4]
C = [7,8,9]
X = [A] + [B] + [C]

print(X)
# [[1, 2, 3], [6, 5, 4], [7, 8, 9]]

print(list(zip(X)))
# [([1, 2, 3],), ([6, 5, 4],), ([7, 8, 9],)]

print(list(zip(*X)))
# [(1, 6, 7), (2, 5, 8), (3, 4, 9)]
더보기
x = A + B
print(x)
# [1, 2, 3, 6, 5, 4]
  • 일종의 피벗? 에도 유용할 듯

 

 

코드 작성 중 확인한 것들

N, X = map(int, input().split())

li = []
for i in range(X):
    X_i = [float(x) for x in input().split()]
    li.append(X_i)
    
print(li)
print(*zip(*li))


"""
[[89.0, 90.0, 78.0, 93.0, 80.0], [90.0, 91.0, 85.0, 88.0, 86.0], [91.0, 92.0, 83.0, 89.0, 90.5]]
(89.0, 90.0, 91.0) (90.0, 91.0, 92.0) (78.0, 85.0, 83.0) (93.0, 88.0, 89.0) (80.0, 86.0, 90.5)
"""

 

 

 

 

 

두 번째 시도

N, X = map(int, input().split())


A = []
for i in range(X):
    A.append(list(map(float, input().split())))

B = list(zip(*A))


for j in B:
    print(sum(j)/len(j))
  • 똑같네 그냥..
  • 리스트 컴프리헨션에서는 언패킹(*) 사용 불가

 

 

참조


 

2. Built-in Functions — Python 2.7.18 documentation

2. Built-in Functions The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. In addition, there are other four built-in functions that are no longer considered essential: apply(

docs.python.org