[Python] 05. 시퀀스 자료형 리스트의 실습, 리스트 선언, 리스트 연결, 리스트 크기, 멤버 체크, 문자열 포맷팅, Tuple, Dictionary의 선언

2017. 8. 2. 11:44·빅데이터 프로그래밍/Python
728x90
반응형

01. 리스트(List), 튜플(Tuple)

- 자료를 나열하여 목록으로 처리

- 리스트(List)는 원본 값을 변경 할 수 있으나 튜플(tuple)은 값을 변경할 수 없으며 사용법이 비슷함.
- 사전(Dictionary)은 키와 값의 구조를 제공(JAVA: Map)

- 문자열의 시작 인덱스는 0부터 시작하며 - 인덱스는 문자열의 끝부터 -1을 시작으로 지정함.

- [시작 인덱스: 마지막 인덱스]: 시작 index부터 마지막 index-1 부분까지 문자열 추출 
- [: 마지막 인덱스]: 처음부터 마지막 index-1 부분까지 문자열 추출 
- [시작 인덱스:] : 시작 index부터 마지막까지 문자열 추출
- [::2]: step을 2로해서 슬라이싱. 

 

1. list 실습

[출력 화면]

 index의 사용
--------------------------------------
cat
bat
rat
elephant
elephant
Hello cat
['cat', 'bat']
[10, 20, 30, 40, 50]
bat
50
 
 슬라이스의 이용
--------------------------------------
['cat', 'bat', 'rat', 'elephant']
['bat', 'rat']
['cat', 'bat', 'rat', 'elephant']
['cat', 'bat']
['bat', 'rat', 'elephant']
['cat', 'bat', 'rat', 'elephant']
4
['cat', '고양이', 'rat', 'elephant']
[1, 2, 3, 'A', 'B', 'C']
[1, 2, 3, 1, 2, 3, 1, 2, 3]
--------------------------------------
['봄', '여름', '가을']
봄
여름
가을
계절 1: 봄
계절 2: 여름
계절 3: 가을
True
False
--------------------------------------
봄: 봄
여름: 여름
가을: 가을
--------------------------------------
2
['봄', '여름', '가을', '크리스마스']
['함박눈', '봄', '여름', '가을', '크리스마스']
['함박눈', '봄', '가을', '크리스마스']
['가을', '봄', '크리스마스', '함박눈']
['함박눈', '크리스마스', '봄', '가을']
['A', 'Z', 'a', 'z']
['A', 'a', 'Z', 'z']
▶list1.py
# -*- coding: utf-8 -*-
print('\n index의 사용')
print("--------------------------------------")
spam = ['cat', 'bat', 'rat', 'elephant'] # list
print(spam[0])
print(spam[1])
print(spam[2])
print(spam[3])
print(spam[-1])

print('Hello ' + spam[0])

spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
print(spam[0])
print(spam[1])
print(spam[0][1])  # bat
print(spam[1][4])  # 50

print("\n 슬라이스의 이용")
print("--------------------------------------")

spam = ['cat', 'bat', 'rat', 'elephant'] # list
print(spam[0:4])
print(spam[1:3])
print(spam)
print(spam[:2])  # ['cat', 'bat']
print(spam[1:])
print(spam[:])
print(len(spam))

spam[1] = '고양이'
print(spam)

spam = [1,2,3] + ['A', 'B', 'C']
print(spam)

spam = [1,2,3] * 3;
print(spam)
print("--------------------------------------")

season=['봄', '여름', '가을', '겨울']
del season[3]
print(season)

for item in season:
    print(item)

# range(5): 0, 1, 2, 4
for index in range(len(season)):
    print('계절 ' + str(index + 1) + ': ' + season[index])

print('봄' in season)
print('겨울' in season)
print("--------------------------------------")

flower, sea, maple = season # 변수의 갯수와 list의 요소는 일치해야함.
print('봄: ' + flower)
print('여름: ' + sea)
print('가을: ' + maple)
print("--------------------------------------")

print(season.index('가을')) # list index
    
season.append('크리스마스') # 마지막에 추가
print(season)

season.insert(0, '함박눈')  # 지정된 index에 추가
print(season)

season.remove('여름')  # 삭제
print(season)

season.sort()  # ascending
print(season)

season.sort(reverse=True)  # decending
print(season)

season=['a', 'z', 'A', 'Z'] # ASCII 기준 정렬
season.sort()
print(season)

season.sort(key=str.lower)
print(season) # ['A', 'a', 'Z', 'z'] 알파벳 문자 순서에의한 정렬
-------------------------------------------------------------------------------------
 

 

2. tuple 실습

[출력 화면]

('hello', 42, 0.5)
(42, 0.5)
3
<class 'str'>
<class 'str'>
<class 'tuple'>
('봄', '여름', '가을', '겨울')
['봄', '여름', '가을', '겨울']
['h', 'e', 'l', 'l', 'o']
('h', 'e', 'l', 'l', 'o')
▶tuple1.py
# -*- coding: utf-8 -*-
eggs = ('hello', 42, 0.5)
print(eggs)
print(eggs[1:3])
print(len(eggs))

print(type('hello')) # <class 'str'>
print(type(('hello'))) # <class 'str'>
print(type(('hello',))) # <class 'tuple'>

season = ['봄', '여름', '가을', '겨울'] # list
season2 = tuple(season) # list -> tuple
print(season2)  

season3 = list(season2) # tuple -> list
print(season3)

season3 = list('hello')  # str -> list
print(season3)

season3 = tuple('hello')  # str -> tuple
print(season3)

-------------------------------------------------------------------------------------

 

 

 

3. list, tuple 실습

[출력 화면]

[6, 2, 3, 4, 5]
------------------------------------------
1
[1, 2, 3]
3
------------------------------------------
[1, 2, 3, 4, 5, 6]
------------------------------------------
5
13
------------------------------------------
False
True
------------------------------------------
(1, 2, 3, 4, 5)
------------------------------------------
1
{'a': 1, 'd': 4, 'c': 3, 'b': 2}
{'a': 1, 'd': 4, 'c': 3, 'b': 7}
4
▶sequence1.py
# -*- coding: utf-8 -*-

# 리스트 선언
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']
list3 = [1, 'a', 'abc', [1, 2, 3, 4, 5], ['a', 'b', 'c']]
list1[0] = 6
print(list1)      # [6, 2, 3, 4, 5]가 출력됨
print("------------------------------------------")

# 리스트 인덱싱
listdata = [1, 2, [1, 2, 3]]
print(listdata[0])     # 1이 출력됨
print(listdata[-1])    # [1, 2, 3]이 출력됨
print(listdata[2][-1])  # [1,2,3]중에서 끝에서 -1번째 3이 출력됨
print("------------------------------------------")

# 리스트 연결
listdata1 = [1, 2, 3]; listdata2 = [4, 5, 6]
print(listdata1 + listdata2)    # [1, 2, 3, 4, 5, 6]이 출력됨
print("------------------------------------------")

# 리스트 크기
strdata1 = 'I love python'
strdata2 = '나는 파이썬을 사랑합니다'
listdata = ['a', 'b', 'c', strdata1, strdata2]
print(len(listdata))     # 5가 출력됨
print(len(listdata[3]))  # 13이 출력됨
print("------------------------------------------")

# 멤버 체크
listdata =[1, 2, 3, 4]
ret1 = 5 in listdata    # False
ret2 = 4 in listdata    # True
print(ret1); print(ret2)
print("------------------------------------------")

# 튜플 선언
tuple1 = (1, 2, 3, 4, 5)
tuple2 = ('a', 'b', 'c')
tuple3 = (1, 'a', 'abc', [1, 2, 3, 4, 5], ['a', 'b', 'c'])
# tuple1[0] = 6

print(tuple1)
print("------------------------------------------")

# 사전 선언
dict1 = {'a':1, 'b':2, 'c':3}
print(dict1['a'])     # 1이 출력됨
dict1['d'] = 4
print(dict1)        # {‘a’:1, ‘b’:2’, ‘c’:3, ‘d’:4}가 출력되나 순서가 틀릴 수 있음
dict1['b'] = 7
print(dict1)        # {‘a’:1, ‘b’:7’, ‘c’:3, ‘d’:4}가 출력되나 순서가 틀릴 수 있음
print(len(dict1))    # 4가 출력됨
 

728x90
반응형

'빅데이터 프로그래밍 > Python' 카테고리의 다른 글

[Python] 07. 제어문 - 반복문(while, for문), for 문 실습  (0) 2017.08.02
[Python] 06. 제어문 - 분기문(if) - 다양한 if문, if문 실습, Template  (2) 2017.08.02
[Python] 04. 시퀀스, 자료형 문자열의 실습, 문자열 선언, 슬라이싱, 연결, 반복, 문자열의 크기, 멤버체크, 문자열 포맷팅  (0) 2017.08.02
[Python] 03. 컴파일, 파이썬 프로그램의 구조, 데이터 형(date type), 연산자(Operator), Library Reference  (0) 2017.08.02
[Python] 02. Eclipse neon3 설치, PyDev 플러그인 설치  (0) 2017.08.02
'빅데이터 프로그래밍/Python' 카테고리의 다른 글
  • [Python] 07. 제어문 - 반복문(while, for문), for 문 실습
  • [Python] 06. 제어문 - 분기문(if) - 다양한 if문, if문 실습, Template
  • [Python] 04. 시퀀스, 자료형 문자열의 실습, 문자열 선언, 슬라이싱, 연결, 반복, 문자열의 크기, 멤버체크, 문자열 포맷팅
  • [Python] 03. 컴파일, 파이썬 프로그램의 구조, 데이터 형(date type), 연산자(Operator), Library Reference
밍글링글링
밍글링글링
mingling - 밍글링, 밍글밍글링. 코드와 어우러지다. IT/ 프로그래밍/소스
    반응형
    250x250
  • 밍글링글링
    mingling
    밍글링글링
  • 전체
    오늘
    어제
    • 밍글링글링 (407) N
      • Flutter (2)
      • 일상생활 (8)
        • 리뷰 (1)
        • 생활정보 (4)
        • 맛집 (0)
        • 여행 (0)
        • 모든정보 (3)
      • JAVA (126)
        • 개념 (6)
        • 예제 (115)
        • Exception (2)
      • C (1)
        • C (1)
        • C++ (0)
        • C# (0)
      • JS (29)
        • JavaScript (18)
        • JQuery (5)
        • AJax (0)
        • NODE.JS (6)
        • Angular.JS 2.0 (0)
      • WEB (87)
        • HTML (6)
        • CSS (61)
        • JSP (20)
        • JSTL (0)
      • FrameWork (8)
        • Spring (8)
        • BootStrap (0)
        • MyBATIS (0)
        • JUnit (0)
      • 외부 라이브러리 (5)
      • 공유 소스 관리 (5)
        • Git (5)
        • SVN (0)
      • 빅데이터 프로그래밍 (37)
        • Python (37)
        • R Programming (0)
      • DB (7)
        • ORACLE (0)
        • MySql (6)
      • Development Tools (7)
        • StarUML (0)
        • eXERD (0)
        • Eclipse (4)
      • SKILL (6)
        • Migration (0)
        • Security (6)
      • MicroSoft (0)
        • Excel (0)
        • Word (0)
      • Android (0)
      • Server (21)
        • Ubuntu (5)
        • Linux (15)
      • IOS (0)
      • XML (0)
      • 미디어 (0)
      • 공지사항 (3)
      • NETWORK (1)
      • 게임 (4)
        • 피파 (1)
        • 리니지M (0)
        • 배틀그라운드 (1)
        • 듀랑고 (2)
      • 세상 이슈 (6)
      • 일렉트론 (0)
      • 대회 소식 (4)
      • 업무 (2)
      • Express, Vue (6)
      • docker (11)
      • svelte (3)
      • 블록체인 (1)
      • IT (10) N
      • Rust (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    에디터 팁
    jsp parameter
    브라우저 자동화
    gitlab 설치
    java casting
    proxy pass
    자바 배열
    vue cli
    svelte
    css list
    nginx
    VS Code 팁
    ssl 인증서 발급
    SSL 인증서
    Node
    ubuntu
    오류
    spring java
    자바 생성자
    css table
    자바 클래스
    css block
    프런트엔드
    nginx ssl 설정
    자바 객체 지향
    자바 exception
    css perspective
    Extension Bisect
    css float
    React Compiler
    css tb
    mysql db
    자바 for문
    servlet class
    nginx ssl 적용
    러스트
    Java Array
    AI 코딩 에이전트
    티스토리 자동화
    클론코딩
    rust linux
    API 설계
    Rust lang
    리눅스 설치
    css transition
    vscode
    lang rust
    vue 설치
    jsp include
    docker
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
밍글링글링
[Python] 05. 시퀀스 자료형 리스트의 실습, 리스트 선언, 리스트 연결, 리스트 크기, 멤버 체크, 문자열 포맷팅, Tuple, Dictionary의 선언
상단으로

티스토리툴바