[Python] PyMongo collection 만들기 Start

BioinformaticsAndMe







MongoDB Collection 생성


: MongoDB 콜렉션(Collection)을 생성하기 위해, 데이터베이스 오브젝트를 사용하여 만들고자 하는 콜렉션 이름을 지정

: MongoDB는 지정된 콜렉션 이름이 존재하지 않았다면, 바로 콜렉션을 생성함

# 'customers'라 불리는 콜렉션 생성

import pymongo myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['mydatabase'] mycol = mydb["customers"]

: MongoDB 콜렉션은 SQL database인 RDBMS의 Table의 위치에 있음



Collection 존재 확인


: MongoDB에서 콜렉션은 Content를 얻을 때까지 생성되지 않음

: 따라서, Document를 먼저 생성해야지만, 콜렉션의 존재를 확인할 수 있음

# 데이터베이스에 포함된 모든 콜렉션 출력

import pymongo myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['mydatabase'] mycol = mydb["customers"] print(mydb.list_collection_names())

['customers']

# 특정 콜렉션이 존재하는지 확인 (앞서 생성한 'customers')

import pymongo myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['mydatabase'] collist = mydb.list_collection_names() if "customers" in collist:

print("The collection exists.")

The collection exists.






#Reference

1) https://www.w3schools.com/python/python_mongodb_getstarted.asp

2) https://www.educba.com/what-is-mongodb/






[Python] PyMongo collection 만들기 End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] PyMongo 데이터베이스 만들기  (0) 2020.01.09
[Python] PyMongo 설치  (0) 2020.01.02
[Python] File Handling  (0) 2019.12.17
[Python] 표준 입력 (User Input)  (0) 2019.12.12
[Python] 파이썬 함수 (Function)  (0) 2019.12.05

[Python] PyMongo 데이터베이스 만들기 Start

BioinformaticsAndMe







MongoDB 데이터베이스 생성


: MongoDB에서 데이터베이스를 생성하기 위해, MongoClient 오브젝트 생성

*'정확한 IP' 및 'DB 이름'을 갖는 연결 URL 설정

: 해당 데이터베이스가 존재하지 않는다면, 아래 명령어로 데이터베이스를 생성하고 연결하게 됨

# 'mydatabase'라 불리는 데이터베이스 생성

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"]




데이터베이스 존재 확인


: MongoDB에서 데이터베이스(DB)는 Content를 얻을 때까지 생성되지 않음

: 따라서, Collection과 Document를 먼저 생성해야지만, 데이터베이스의 존재를 확인할 수 있음


# 사용중인 시스템의 모든 데이터베이스를 출력

import pymongo myclient = pymongo.MongoClient('mongodb://localhost:27017/') print(myclient.list_database_names())

['admin', 'local', 'mydatabase']

# 특정 DB가 존재하는지 확인 (앞서 생성한 'mydatabase')

import pymongo myclient = pymongo.MongoClient('mongodb://localhost:27017/') dblist = myclient.list_database_names() if "mydatabase" in dblist:

print("The database exists.")

The database exists.






#Reference

1) https://www.w3schools.com/python/python_mongodb_getstarted.asp

2) https://www.mdpi.com/1999-5903/11/4/83/htm






[Python] PyMongo 데이터베이스 만들기 End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] PyMongo collection 만들기  (0) 2020.01.16
[Python] PyMongo 설치  (0) 2020.01.02
[Python] File Handling  (0) 2019.12.17
[Python] 표준 입력 (User Input)  (0) 2019.12.12
[Python] 파이썬 함수 (Function)  (0) 2019.12.05

[Python] PyMongo 설치 Start

BioinformaticsAndMe







파이썬 PyMongo


: 파이썬에서는 DBMS(DataBase Management System)을 간단한 명령어로 운용할 수 있음

: 파이썬의 PyMongo 패키지로 NoSQL 데이터베이스인 MongoDB에 접근함

*MongoDB는 JSON 형태로 데이터를 저장하므로, DB를 유연하게 확장 가능

*https://www.mongodb.com

: 파이썬 PIP을 사용하여, PyMongo를 설치함

# 파이썬 PIP 경로에서 아래 커맨드를 입력

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install pymongo

: MongoDB 드라이버가 다운되고 설치됨





PyMongo 설치 확인


: pymongo의 성공적인 설치 확인을 위해, pymongo 로딩을 테스트

# pymongo 라이브러리 로딩

import pymongo

특별한 에러가 발생하지 않는다면,

pymongo 모듈이 정상적으로 설치됐고,

MongoDB를 사용할 준비가 된 것.






#Reference

1) https://www.w3schools.com/python/python_mongodb_getstarted.asp

2) https://www.mongodb.com

3) https://www.youtube.com/watch?v=P1Qbf3A_E6U





[Python] PyMongo 설치 End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] PyMongo collection 만들기  (0) 2020.01.16
[Python] PyMongo 데이터베이스 만들기  (0) 2020.01.09
[Python] File Handling  (0) 2019.12.17
[Python] 표준 입력 (User Input)  (0) 2019.12.12
[Python] 파이썬 함수 (Function)  (0) 2019.12.05

[Python] File Handling Start

BioinformaticsAndMe







File handling


: 파이썬 파일 처리에는 파일 생성/읽기/업데이트/삭제 등의 여러 기능이 존재

: 파일처리를 위해선 2가지 매개변수(파일명, 모드)를 갖는 'open() 함수'를 사용

: 파일 open에는 6가지 모드(mode)가 존재

1) "r" - Read - 파일 읽기(기본값)

2) "a" - Append - 파일 덧붙이기

3) "w" - Write - 파일 쓰기

4) "x" - Create - 특정 파일 생성

5) "t" - Text - 텍스트 모드(기본값)

6) "b" - Binary - 바이너리 모드(이미지 등)

# 파이썬 파일 읽기 예제

f = open("demofile.txt")


# 위 코드와 같음 (기본값이라 생략됨)

f = open("demofile.txt", "rt")




1. 파이썬 Read


demofile.txt

# demofile.txt 파일 읽기

f = open("demofile.txt", "r")

print(f.read())

Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!

# read(숫자)로 반환되는 문자수를 지정할 수 있음

f = open("demofile.txt", "r") print(f.read(5))

Hello

# readline() 메소드를 통해, 파일의 한 줄만을 반환

f = open("demofile.txt", "r") print(f.readline())

Hello! Welcome to demofile.txt

# 파일 처리가 끝난 뒤, 반드시 close() 메소드를 사용함

f = open("demofile.txt", "r") print(f.readline()) f.close()

Hello! Welcome to demofile.txt




2. 파이썬 Append


# 파일 끝에 덧붙이기

f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() # 덧붙여진 파일을 다시 읽고, 결과 확인 f = open("demofile2.txt", "r") print(f.read())

Hello! Welcome to demofile2.txt This file is for testing purposes. Good Luck!Now the file has more content!




3. 파이썬 Write


# 파일 생성하고 쓰기

f = open("demofile3.txt", "w") f.write("Woops! I have deleted the content!") f.close()

# 쓰여진 파일을 읽고, 결과 확인 f = open("demofile3.txt", "r") print(f.read())

Woops! I have deleted the content!





#Reference

1) https://www.w3schools.com/python/python_file_handling.asp

2) https://data-flair.training/blogs/file-handling-in-python/





[Python] File Handling End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] PyMongo 데이터베이스 만들기  (0) 2020.01.09
[Python] PyMongo 설치  (0) 2020.01.02
[Python] 표준 입력 (User Input)  (0) 2019.12.12
[Python] 파이썬 함수 (Function)  (0) 2019.12.05
[Python] 파이썬 반복문  (0) 2019.11.28

[Python] 표준 입력 (User Input) Start

BioinformaticsAndMe







파이썬 표준 입력 (Python Input function)


: 파이썬은 사용자에게 임의의 정보를 입력하도록 요청할 수 있는 Input function이 존재

: 표준 입력 방법은 'Python3' 및 'Python2'에서 서로 다름




1. 파이썬 3 표준 입력


: 파이썬 3는 Input() 메소드 사용

# 유저 이름 입력받기

username = input("Enter username:") print("Username is: " + username)

Enter username: Gold Username is: Gold




2. 파이썬 2 표준 입력


: 파이썬 2는 raw_Input() 메소드 사용

# 유저 이름 입력받기

username = raw_input("Enter username:") print("Username is: " + username)

Enter username: Silver Username is: Silver





#Reference

1) https://www.w3schools.com/python/python_user_input.asp

2) https://pynative.com/python-input-function-get-user-input/





[Python] 표준 입력 (User Input) End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] PyMongo 설치  (0) 2020.01.02
[Python] File Handling  (0) 2019.12.17
[Python] 파이썬 함수 (Function)  (0) 2019.12.05
[Python] 파이썬 반복문  (0) 2019.11.28
[Python] 파이썬 조건문  (0) 2019.11.21

[Python] 파이썬 함수 (Function) Start

BioinformaticsAndMe







파이썬 함수 (Python Function)


: 파이썬 함수는 호출할 때만 실행되는 코드 단위

: 매개변수를 포함한 데이터를 함수를 통해 전달 가능

: 중복되는 스크립트를 줄여, 프로그램의 가독성을 높여줌






1. 함수(function) 만들기


: 파이썬 function을 만들기 위해서, 'def' 키워드로 선언을 해줘야함

# my_function 함수 만들기

def my_function(): print("Hello from a function")

# my_function 함수 호출

my_function()

Hello from a function




2. 함수 매개변수(parameter)


: 입력된 정보가 매개변수(parameter)를 통해 함수에 전달됨

*매개변수(parameter) - 입력된 정보가 저장되는 변수

# fname 매개변수를 사용한 함수 만들기

def my_function(fname): print(fname + " Refsnes")

# 아래 입력된 정보들은 함수의 매개변수로 인지되어 호출

my_function("Emil") my_function("Tobias") my_function("Linus")

Emil Refsnes Tobias Refsnes Linus Refsnes

# 입력된 정보없이 함수를 호출하면, default로 지정된 값이 출력됨

def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil")

I am from Sweden I am from India I am from Norway I am from Brazil




3. 함수 return


: 파이썬 함수 내에 사용되는 'return'은 결과값을 반환하기 위해 사용됨

# return을 통해, 연산 결과를 반환

def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9))

15 25 45





#Reference

1) https://www.w3schools.com/python/python_functions.asp

2) https://www.askpython.com/python/python-functions





[Python] 파이썬 함수 (Function) End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] File Handling  (0) 2019.12.17
[Python] 표준 입력 (User Input)  (0) 2019.12.12
[Python] 파이썬 반복문  (0) 2019.11.28
[Python] 파이썬 조건문  (0) 2019.11.21
[Python] 사전(Dictionary)  (0) 2019.11.05

[Python] 파이썬 반복문 Start

BioinformaticsAndMe







0. 파이썬 반복문 (Python Loop)


: 파이썬 반복문에는 'FOR Loop' 및 'WHILE loop'가 존재

1) FOR 루프 - 리스트/튜플/딕셔너리 등의 시퀀스 집합을 반복

2) WHILE 루프 - 참인 조건 상황에서 거짓으로 될때까지 반복





1. FOR 반복문


# for 반복문 기본 형태

fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)

apple banana cherry

# 문자열은 각각의 문자를 요소로 인식하여 반복

for x in "banana":   print(x)

b a n a n a

# break 문으로 모든 항목을 반복하기 전 루프 중지

fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana":

break        #banana 항목이 들어오면, for 반복문을 중단하고 루프 밖으로 나옴

apple banana

# continue 문으로 반복문의 현재 항목을 건너뛰고 계속 루프 진행

fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue        #banana 항목이 들어오면, banana를 건너뛰고 계속해서 루프 수행

print(x)

apple cherry

# 아래의 range 함수는 2부터 30전까지(~29) 출력하도록 세팅

# 단, 세번째 매개변수를 3으로 입력하여 +3씩 루프를 지정

for x in range(2, 30, 3): print(x)

2 5 8 11 14 17 20 23 26 29

# for 반복문에 실행할 명령이 없을 때, pass 문을 사용하여 오류를 피함 (단지, 아무것도 출력되지 않음)

for x in [0, 1, 2]: pass







2. WHILE 반복문


# while 반복문 기본 형태 (조건이 True를 유지할 때까지 루프)

i = 1 while i < 6: print(i)

1 2 3 4 5

# break 문으로 조건이 True인 경우에도 루프 중단

i = 1 while i < 6: print(i) if (i == 3): break i += 1

1

2

3

# continue 문으로 반복문의 현재 항목을 건너뛰고 계속 루프 진행

# for 반복문에서 사용되는 특수 함수들은 거의 대부분 while 반복문에서도 동일하게 사용됨

i = 0 while i < 6: i += 1 if i == 3: continue

print(i)

1 2 4 5 6






#Reference

1) https://www.w3schools.com/python/python_for_loops.asp

2) https://www.w3schools.com/python/python_while_loops.asp

3) https://www.datacamp.com/community/tutorials/loops-python-tutorial

4) https://www.techbeamers.com/python-for-loop/

5) https://www.techbeamers.com/python-while-loop/





[Python] 파이썬 반복문 End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] 표준 입력 (User Input)  (0) 2019.12.12
[Python] 파이썬 함수 (Function)  (0) 2019.12.05
[Python] 파이썬 조건문  (0) 2019.11.21
[Python] 사전(Dictionary)  (0) 2019.11.05
[Python] 리스트(List)  (0) 2019.10.30

[Python] 파이썬 조건문 Start

BioinformaticsAndMe






1. Python conditional statement (if 조건문)


: 파이썬 조건문은 주어진 조건(condition)이 '참(TRUE) 또는 거짓(FALSE)'인지에 따라 명령을 수행함

: 조건문은 여러 형태로 선언될 수 있으며, 주로 'if 및 else' 키워드(keyword)로 작성됨

: 조건문(condition)에는 다양한 논리연산자가 사용됨

ㄱ) a와 b가 같음 ▶ a == b

ㄴ) a와 b가 같지 않음 ▶ a == b

ㄷ) a가 b보다 작음 ▶ a < b

ㄹ) a가 b보다 작거나 같음 ▶ a <= b

ㅁ) a가 b보다 큼 ▶ a > b

ㅂ) a가 b보다 크거나 같음 ▶ a >= b

# b가 a보다 큰지 검사하는 조건문

a = 33 b = 200 if b > a: print("b is greater than a")

b is greater than a

# 파이썬 조건문은 반드시 들여쓰기(Indentation) 수행

a = 33 b = 200 if b > a: print("b is greater than a")     #들여쓰기를 안했기에 Indentation error 발생

File "demo_if_error.py", line 4 print("b is greater than a") ^ IndentationError: expected an indented block




2. elif, else 조건문


: elif 구문은 먼저 사용된 'if 조건'이 참이 아닐 때 실행됨

: else 구문은 먼저 사용된 'if 조건 및 elif 조건' 모두가 참이 아닐 때 실행됨

# if, elif, else 구문을 사용해 조건문을 정의

a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")

a is greater than b

# elif없이 else만 사용 가능함 (또한, else없이 if만 사용 가능함)

a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a")

b is not greater than a

# if, else 구문은 같은 줄에 작성 가능함

a = 2 b = 330

print("A") if a > b else print("B")

B




3. and, or 구문


: 'and' 는 논리 연산자로 조건문들의 교집합 선언

: 'or' 은 논리 연산자로 조건문들의 합집합 선언

# a가 b보다 크고, 동시에 c가 a보다 큰지 검사하는 조건문

a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True")

Both conditions are True

# a가 b보다 크거나, 또는 a가 c보다 큰지 검사하는 조건문

a = 200 b = 33 c = 500 if a > b or a > c:   print("At least one of the conditions is True")

At least one of the conditions is True

# if 조건이 참일 때, pass 구문을 사용하면 error없이 스크립트가 수행됨

a = 33 b = 200 if b > a: pass





4. Nested If 구문


: if 구문 내부로 계속해서 if 조건문을 생성할 수 있음 (=Nested if)

# Nested if 조건문 정의

x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.")

Above ten, and also above 20!







#Reference

1) https://www.w3schools.com/python/python_conditions.asp

2) https://data36.com/python-if-statements-explained-data-science-basics/





[Python] 파이썬 조건문 End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] 파이썬 함수 (Function)  (0) 2019.12.05
[Python] 파이썬 반복문  (0) 2019.11.28
[Python] 사전(Dictionary)  (0) 2019.11.05
[Python] 리스트(List)  (0) 2019.10.30
[Python] 문자열(String)  (0) 2019.10.24

[Python] 사전(Dictionary) Start

BioinformaticsAndMe





1. Python Dictionary


: 파이썬 사전(Dictionary)는 키(key)와 값(value)을 한 쌍으로 갖는 집합

: 요소의 순서가 없고, 자유롭게 변경 가능하며, 중복을 허용하지 않음

: 딕셔너리는 중괄호로 정의함

# 딕셔너리 thisdict 출력

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}



2. 딕셔너리 Indexing


: Key name을 통해, 딕셔너리 항목에 접근할 수 있음

# 딕셔너리의 특정 Key에 매칭되는 Value를 출력

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = thisdict["model"] print(x)

Mustang

# get 함수로 동일한 결과를 출력할 수 있음

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = thisdict.get("model") print(x)

Mustang



3. 딕셔너리 항목 변경


: 딕셔너리 특정 Key에 매칭되는 Value 값을 변경할 수 있음

# 'year'의 1964를 2018로 변경

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["year"] = 2018

print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}



4. 딕셔너리 Loop


: 파이썬 for문을 통해, 딕셔너리의 Key와 Value를 각각 또는 함께 출력할 수 있음

# 딕셔너리의 모든 Key 출력

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict: print(x)

brand model year

# 딕셔너리의 모든 Value 출력

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict: print(thisdict[x])

Ford Mustang 1964

# value 함수를 통해, 딕셔너리의 모든 Value 출력

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict.values(): print(x)

Ford Mustang 1964

# item 함수를 통해, 딕셔너리의 모든 Key 및 Value 출력

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x, y in thisdict.items(): print(x, y)

brand Ford model Mustang year 1964



5. 딕셔너리 Key 확인


: 딕셔너리 내 특정 Key가 존재하는 'in' 오퍼레이터로 확인함

# 'model'이 thisdict 딕셔너리에 존재하는 Key인지 확인

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary")

Yes, 'model' is one of the keys in the thisdict dictionary



6. 딕셔너리 항목 추가


: 같은 딕셔너리에 특정 Key와 Value를 재할당함으로써, 새로운 항목을 추가함

# 'color' Key 및 'red' Value 항목 추가

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}





파이썬 딕셔너리 함수


함수

기능

실행

결과

clear

딕셔너리 모든 항목 제거

car = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

car.clear()

print(car)

{ }

copy

딕셔너리 복사

car = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

x = car.copy()

print(x)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

keys

딕셔너리 내 모든 키를 리턴

car = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

x = car.keys()

print(x)

dict_keys(['brand', 'model', 'year'])

pop

딕셔너리 내 특정 키 항목 제거

car = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

car.pop("model")

print(car)

{'brand': 'Ford', 'year': 1964}

update

딕셔너리에 새로운 항목을 추가해 업데이트

car = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

car.update({"color": "White"})

print(car)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}

len

딕셔너리 항목의 개수

thisdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

print(len(thisdict))

3






#Reference

1) https://www.w3schools.com/python/python_dictionaries.asp

2) https://bjc.edc.org/bjc-r/cur/programming/old-labs/python/comparing_dicts_lists.html?topic=nyc_bjc%2FNA-python.topic

3) http://www.trytoprogram.com/python-programming/python-dictionary/





[Python] 사전(Dictionary) End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] 파이썬 반복문  (0) 2019.11.28
[Python] 파이썬 조건문  (0) 2019.11.21
[Python] 리스트(List)  (0) 2019.10.30
[Python] 문자열(String)  (0) 2019.10.24
[Python] 연산자(Operator)  (0) 2019.10.18

[Python] 리스트(List) Start

BioinformaticsAndMe





1. Python List


: 파이썬 리스트는 순서를 가진 집합으로, 리스트는 대괄호( [ ] )로 선언됨

: 자유롭게 변경이 가능하며, 중복을 허용 

→ ['a', 'b', 'c', 'a']

# 리스트 thislist 출력

thislist = ["apple", "banana", "cherry"] print(thislist)

['apple', 'banana', 'cherry']



2. 리스트 Indexing


: 인덱스 번호를 통해, 리스트 항목에 접근할 수 있음

# 리스트의 Index1을 출력

thislist = ["apple", "banana", "cherry"] print(thislist[1])

banana

# 리스트의 Negative Indexing

thislist = ["apple", "banana", "cherry"] print(thislist[-1])

cherry



3. 리스트 Slicing


: 슬라이스 구문(':', 콜론)을 사용하여 문자열 일부를 리턴할 수 있음

: 첫번째 항목의 인덱스는 0

→ [start index]:[end index]

# Index2 ~ Index4 문자 슬라이싱 (Index5는 포함되지 않음)

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5])

['cherry', 'orange', 'kiwi']



4. 리스트 항목 변경


: 리스트의 특정 항목값을 변경하기 위해서, 인덱스 번호를 참조함

# 'banana'를 'blackcurrant'로 변경

thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist)

['apple', 'blackcurrant', 'cherry']



5. 리스트 항목 Check


: 특정 항목이 리스트 내에 존재하는지, 'in' 연산자를 사용해서 확인함

# 'apple'이 thislist에 존재하는지 확인 (존재한다면, 결과 출력)

thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list")

Yes, 'apple' is in the fruits list



6. 리스트 join


: 두 개의 리스트를 합치기 위해, 간단하게 '+' 연산자를 사용

# list1과 list2 리스트 값 합치기

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3] list3 = list1 + list2 print(list3)

['a', 'b', 'c', 1, 2, 3]




파이썬 리스트 함수


함수

기능

실행

결과

append

리스트 끝에 항목 추가

fruits = ['apple', 'banana', 'cherry']

fruits.append("orange")

print(fruits)

['apple', 'banana', 'cherry', 'orange']

clear

리스트 모든 항목 제거

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

fruits.clear()

print(fruits)

[ ]

copy

리스트 복사

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

x = fruits.copy()

print(x)

['apple', 'banana', 'cherry']

count

리스트 내 특정 항목을 카운트

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

x = fruits.count("cherry")

print(x)

1

extend

리스트 끝에 다른 리스트 추가

fruits = ['apple', 'banana']

cars = ['Ford', 'BMW', 'Volvo']

fruits.extend(cars)

print(fruits)

['apple', 'banana', 'Ford', 'BMW', 'Volvo']

index

리스트 내 특정값의 첫번째 인덱스 리턴

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")

print(x)

2

insert

리스트 내 특정 위치에 항목 추가

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")

print(fruits)

['apple', 'orange', 'banana', 'cherry']

pop

리스트 내 특정 위치 항목 제거

fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)

print(fruits)

['apple', 'cherry']

remove

리스트 내 특정값을 갖는 항목 제거

fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

print(fruits)

['apple', 'cherry']

reverse

리스트의 순서 뒤집기

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

print(fruits)

['cherry', 'banana', 'apple']

sort

 리스트 값 정렬

cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)

['BMW', 'Ford', 'Volvo']





#Reference

1) https://www.w3schools.com/python/python_lists.asp

2) https://realpython.com/python-lists-tuples/





[Python] 리스트(List) End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] 파이썬 조건문  (0) 2019.11.21
[Python] 사전(Dictionary)  (0) 2019.11.05
[Python] 문자열(String)  (0) 2019.10.24
[Python] 연산자(Operator)  (0) 2019.10.18
[Python] 자료형(Data type)  (0) 2019.10.15

+ Recent posts