[python] 리스트 변수를 반복문 돌리기 예시

1 minute read
 1students = []
 2student1_info = {
 3    "first_name": "Martin",
 4    "las_name" : "Lawrence",
 5    "student_no": 9854
 6
 7}
 8
 9student2_info = {
10    "first_name": "Robert",
11    "las_name" : "Gant",
12    "student_no": 6790
13
14}
15
16student3_info = {
17    "first_name": "George",
18    "las_name" : "Murphy",
19    "student_no": 4728
20
21}
22
23for i in range(1, 4):
24    students.append(eval('student%d_info'% (i)))
25
26print(students)
  • eval() : 실행 가능한 문자열을 입력 받아 실행한 결과값을 리턴하는 함수이다.

    1>>> eval('1+2')
    23
    3>>> eval("'hi' + 'a'")
    4'hia'
    5>>> eval('divmod(4, 3)')
    6(1, 1)
    

  • append() : 객체를 맨 뒤에 추가해주는 함수이다.

    1>>> x = [1, 2, 3]
    2>>> x.append([4, 5, 6])
    3>>> print (x)
    4[1, 2, 3, [4, 5, 6]]
    

  • extend() : 여러개의 값을 확장시킬 수 있는 함수이다. 함수로 전달되는 인수에는 리스트만 올 수 있다.

1>>> x = [1, 2, 3]
2>>> x.extend([4, 5, 6])
3>>> print (x)
4[1, 2, 3, 4, 5, 6]