본문 바로가기
Improvement/인공지능개발

[인공지능 개발] #4. 파이썬 기초(3)_시퀀스타입(리스트,튜플,문자열)

by 까따이 2024. 10. 13.
반응형

1. Sequene types

1-1. 리스트

- fruits = ["apple", "banana", "cherry"]

  print(fruits)

  print(type(fruits))

  print(fruits[2])  # 모든 숫자는 0부터 시작한다.

  print(fruits[-1])  # -는 뒤에서부터 숫자를 가져온다.

출력: ['apple', 'banana', 'cherry' ]

        <class 'list'>

        'cherry'

        'cherry'

 

- numbers = [100, 200, 300, 400]

  numbers[1] = 0  #리스트의 값을 변환할 수 있다.

  numbers.append("500") #리스트의 값을 추가할 수 있다.  

  print(numbers)

출력: ['100', '0', '300', '400', '500' ]

 

- list1 = [[1,2,3],[4,5,6,]]  #이것은 2차원 행렬이다.

  print(list1[0][2])  #1행 3열을 호출하는 것이다.

출력: 3

 

1-2. 튜플

리스트와 유사하지만 한 번 생성된 값을 변경할 수 없다. 

 

- point = (1, 2)

  print(point)

  print("x: ", point[0], "y: ", point[1])

출력: (1, 2)

         x: 1 y: 2

 

1-3. 문자열

- Welcome = "Hello, World!"

  print(Welcome)

  print(type(Welcome))

  print(welcome[3],welcome[8]) #문자열에서 해당 순서에 있는 숫자를 추출한다.

출력: Hello, World!

        <class 'str'>

        l W

 

- print(range(10)) 

  print(list(range(3,10))) #범위는 3~9까지의 객체

출력: range(0, 10)

         [3, 4, 5, 6, 7, 8, 9]

 

- print(list(range(10,0))) #기본값으로 +1값이 설정된다.

출력 불가

 

- print(list(range(10,0,-1))) #  -1로 감소하는 값을 적어줘야 출력이 가능하다.

출력: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

 

- Welcome = "Hello, World!"  # 문자열 슬라이싱을 통해 자를 수 있다.

  print(Welcome[0:5])

  print(Welcome[-6:])

출력: Hello

         World!

 

1-4. 시퀀스 연산

리스트, 튜플, 문자열 모두 연산을 사용할 수 있다.

 

[시퀀스 반복]

- fruits = ["apple", "banana", "cherry"]

  print(fruits * 2)

출력: ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry'  ]

 

[시퀀스 연결]

- fruits = ["apple", "banana", "cherry"]

  print(fruits + "kiwi", "melon")

출력: ['apple', 'banana', 'cherry', 'kiwi', 'melon' ]

 

[시퀀스 길이 출력]

- fruits = ["apple", "banana", "cherry"]

  Welcome = "Hello, World!"

print(len(fruits))

print(len(Welcome))

출력: 3

        13

 

[연습문제]

1. 세 과일 이름을 리스트로 만들고 이를 출력하시오

 

2. 좌표를 나타내는 튜플을 만들고 x와 y값을 출력하시오

3. 문자열을 입력받고 첫 문자와 마지막 문자를 출력하는 프로그램을 만드시오.

반응형