반응형

- anaconda / pyCharm 환경

import sys
from PyQt5.QtWidgets import *
from PyQt5.QAxContainer import *

 

- QAxContainer import 에서 에러가 난다.

 

https://stackoverflow.com/questions/56451682/pyqt5-and-anaconda-modulenotfounderror-no-module-named-pyqt5

 

PyQt5 and Anaconda: ModuleNotFoundError: No module named 'PyQt5'

I made a totally new, blank environment in anaconda and activated it. I then did "conda install pyqt5", however when importing modules, like in from PyQt5.QtWidgets import QApplication, QWidget my

stackoverflow.com

- 여기에서 해결점을 찾았다.

 

- 사이트에 있는 해결점 내용

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

The following worked for me:

  • Install pyqt5 using pip install pyqt5.
  • Then use from PyQt5.QtWidgets import QApplication, QWidget in Python (note the different case!)

UPDATE:

When using virtual environments you have to be sure you are doing all the stuff in the same virtual environment. To do this, first activate your environment, then just use the python command for everything and avoid using the py or pip commands directly.

The following are some steps to help you debugging your problem:

  • First activate your virtual environment. I don't have experience with anaconda, but I assume it's similar to venv or virtualenv (i.e. just calling the corresponding activate script) and you know how to do this.
  • Then:
    • Run python -V to check your Python version.
    • Run python -m pip -V to check the version of PIP. Note that this also prints the location of the pip module. This should be in your virtual environment!
    • Run python -m pip list to see which PIP packages are installed. PyQt5 should be included in this list. If not, run python -m pip install pyqt5 and try again.
    • Run python -m pip show pyqt5 to show information about the pyqt5 module. This also should include a location inside your virtual environment.
    • Run python -c "import PyQt5" to check if the PyQt5 module can be imported. This should print nothing (no ModuleNotFoundError).
    • Run your script using python xyz.py. Don't use the command xyz.py, since in that case the Windows registry determines the "open action", which is likely to run the script using your most recently installed Python version instead of the version from your virtual environment!

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

 

1. Anaconda Prompt 를 실행한다. ( 윈도우 시작키)

 

2. Anaconda Prompt 콘솔창

# pyqt5 설치
> pip install pyqt5

# 버전체크
> python -V

# pip 버전체크와 경로
> python -m pip -V

# pip 패키지가 설치된 목록
# 목록 중에서 pyqt5 를 확인한다.
> python -m pip list

# 목록중에서 pyqt5 없으면 설치
> python -m pip install pyqt5

# pyqt5 정보를 볼수있고, 경로 확인도 볼수 있다.
> python -m pip show pyqt5

# PyQt5 import 한다. - "여기서 주의점은 대소문자 주의"
> python -c "import PyQt5"

 

짧은 영어지식으로 번역함. ㅎ

 

반응형

'IT > Python' 카테고리의 다른 글

Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

- GUI(Graphical User Interface)
- TUI(Text-based User Interface) : 지금까지 파이썬을 통해 만든 프로그램 기반

Python GUI 프로그래밍은 wxPython, PyQt, TkInter 등과 같은 패키지를 사용한다.
TkInter 는 파이썬의 공식적인 GUI 패키지로서 별도의 프로그램을 설치하지 않고도 바로 사용할 수 있다.
TkInter 는 복잡한 프로그램을 개발하기는 부족한 면이 있어, wxPython, PyQt 를 많이 사용한다.

 

http://www.wxpython.org/ 

 

Welcome to wxPython!

All about wxPython, the cross-platform GUI toolkit for the Python language

wxpython.org

https://riverbankcomputing.com/ 

 

Riverbank Computing | News

News PyQt-builder 1.3.2 Released 20 April 2020 PyQt-builder v1.3.2 has been released. This is a minor bug-fix release. pyqtdeploy v2.5.1 Released 15 April 2020 pyqtdeploy v2.5.1 has been released. This is a minor big-fix release. pyqtdeploy v2.5.0 Released

riverbankcomputing.com

 

- PyQt
Qt GUI 프레임워크의 파이썬 바인딩이며, 개발에 널리 쓰이는 크로스 플랫폼 프레임워크로 C++ 라는 프로그래밍 언어를 사용해서 프로그래밍한다.
크로스플랫폼 프레임워크 : 윈도우나 리눅스와 같은 운영체제에 상관없이 같은 코드로 각 운영체제에서 동작하는 프로그램 개발을 지원하는 것을 의미

- from PyQt5.QtWidgets import *
PyQt5 라는 디렉토리의 QtWidgets 파일에 있는 모든 것(*)을 임포트하라는 의미
PyQt5 Anaconda3 에 설치되어 있음.

 

- QLabel 

# 라벨 Hello World 
import sys
from PyQt5.QtWidgets import *

app = QApplication(sys.argv)
print(sys.argv)
label = QLabel("Hello World")
label.show()
app.exec_()

 

- QPushButton

# 버튼 생성
import sys
from PyQt5.QtWidgets import *

app = QApplication(sys.argv)
label = QPushButton("Quit")
label.show()
app.exec_()

 


- 위젯
QGroupBox, QLabel, QTextEdit, QDateEdit, QTimeEdit, QLineEdit
다양한 위젯이 사용 / 한 위젯은 다른 위젯에 포함될 수 있다.
최상위 위젯은 윈도우(window) 이다. - QMainWindow , QDialog 클래스를 일반적으로 사용

 

# QMainWindow
import sys
from PyQt5.QtWidgets import *

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyStock")
        self.setGeometry(300, 300, 300, 400)

        # 이벤트처리
        btn1 = QPushButton("click", self)
        btn1.move(20, 20)
        btn1.clicked.connect(self.btn1_clicked)

    def btn1_clicked(self):
        QMessageBox.about(self, "message", "Clicked")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = MyWindow()
    myWindow.show()
    app.exec_()

 

- super().__init__() 의 명시적인 호출 예제

# super().__init__() 의 명시적인 호출 예제

class Parent:
    house = "parent"
    def __init__(self):
        self.money = 10000

class Child1(Parent):
    def __init__(self):
        super().__init__()
        pass

class Child2(Parent):
    def __init__(self):
        pass

child1 = Child1()
child2 = Child2()

print("child1", dir(child1))
print("child2", dir(child2))

 

 

반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

COM ( Component Object Model )

- 마이크로소프트에서 개발한 기술

 

- explorer open

# explorer open
explore = win32com.client.Dispatch("InternetExplorer.Application")
explore.Visible = True

 

- word open

# word open
word = win32com.client.Dispatch("Word.Application")
word.Visible = True

 

- excel open write

# excel open write
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets("Sheet1")
ws.Cells(1,1).Value = "hello world"
wb.SaveAs("C:\\Users\\User\\Desktop\\test.xlsx")
excel.Quit()

 

- excel open read

# excel open read
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
wb = excel.Workbooks.Open("C:\\Users\\User\\Desktop\\test.xlsx")
ws = wb.ActiveSheet
print( ws.Cells(1,1).Value )
excel.Quit()

 

- excel open read write color

- ColorIndex 는 0 ~ 56 범위를 가지며, 마이크로소프트에서 제공하는 MSDN 참고 또는 구글링

# excel open read write color 
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
wb = excel.Workbooks.Open("C:\\Users\\User\\Desktop\\test.xlsx")
ws = wb.ActiveSheet
ws.Cells(1,2).Value = "hello"
ws.Range("C1").value = "world"
ws.Range("C1").Interior.ColorIndex = 20 # 0 ~ 56 마이크로소프트에서 제공하는 MSDN 참고
ws.Range("A2:C4").Interior.ColorIndex = 30

 

 

반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

1. Python IDE ( Integrated Development Environment )

- 파이썬 통합개발환경

- 비주얼 스튜디오 기반 PTVS ( Python Tools for Visual Studio ) / 이클립스 기반 PyDev / JetBrains의 PyCharm

 

- 비주얼 스튜디오 기반 PTVS ( Python Tools for Visual Studio )

https://github.com/microsoft/PTVS

 

microsoft/PTVS

Python Tools for Visual Studio. Contribute to microsoft/PTVS development by creating an account on GitHub.

github.com

 

- 이클립스 기반 PyDev

http://www.pydev.org/

 

PyDev

Important First time users are strongly advised to read the Getting started guide which explains how to properly configure PyDev. LiClipse The recommended way of using PyDev is bundled in LiClipse, which provides PyDev builtin as well as support for other

www.pydev.org

 

- JetBrains의 PyCharm

https://www.jetbrains.com/pycharm/

 

PyCharm: the Python IDE for Professional Developers by JetBrains

The Python & Django IDE with intelligent code completion, on-the-fly error checking, quick-fixes, and much more...

www.jetbrains.com

- PyCharm 이 가장 인기가 좋음

- Professional / Community 버전이 있으며

- 유료 / 무료 버전이다.

 

- Community 버전을 다운로드(https://www.jetbrains.com/pycharm/download/#section=windows) 받아서 설치

- 설치 후 프로젝트 생성시, 프로젝트 인터프리터를 잡아주어야 한다.

- Existing interpreter : [사용자경로]\anaconda3\python.exe

 

- py 파일을 만들고

- print("Hello World~~~~!!!!") 

- 공부 끝~~~~!?!?!?!!!??

 

반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

1. 파일읽기

- 메모장을 열어서 아무 내용을 작성하고, 저장한다.

- 디렉토리 구분자는 '\\' OR '/' 을 사용

( C:/Users/User/Desktop/test.txt )

# 읽기모드 'r'
# 텍스트 파일 't'
f = open("C:/Users/User/Desktop/test.txt", "rt")

# 각 라인을 리스트에 넣은 후 리스트를 반환
lines = f.readlines()
lines

# 줄바꿈 \n 제거
for line in lines :
  print( line, end="")

# OR
for line in lines :
  print( line.split("\n")[0] )

 

2. 파일쓰기

- 빈문서 파일을 만든다 / 문서를 기록한다 / 문서 파일을 닫는다

# 빈문서 파일을 만든다.
# 파일쓰기 'w'
f = open("C:/Users/User/Desktop/bin_file.txt", "wt")
f.write("hi~\n")
f.write("My name is sangJJang\n")
f.close()

 

반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

1. 클래스

- class

- 클래스 내부에 정의된 함수인 메서드의 첫번째 인자는 반드시 self 이어야 한다. ( 그냥 외울 것 )

# class 선언
class Test :
    def set_test(self, name, msg) :
        self.name = name
        self.msg = msg
    def print_test(self) :
        print("------------------------")
        print("name : ", self.name)
        print("msg : ", self.msg)
        print("------------------------")

# 인스턴스 생성
test01 = Test()
test01
type(test01)

test01.set_test("홍길동", "안녕하세요")

test01.name
test01.msg

test01.print_test()

 

- 생성자

- 인스턴스 생성과 동시에 자동으로 호출되는 메서드인 생성자가 존재( 객체지향 프로그래밍 언어에도 있는 개념 )

- __init__(self)와 같은 이름의 메서드

- 파이썬 클래스에서 __ 로 시작하는 함수는 모두 특별한 메서드를 의미

# init - initialize 초기화하다
class MyTest :
    def __init__(self) :
        print( "객체가 생성되었습니다" )
        
myTest = MyTest()
# init - initialize 초기화하다
class MyTest :
    def __init__(self, name, msg) :
        self.name = name
        self.msg = msg
    def print_test(self) :
        print("------------------------")
        print("name : ", self.name)
        print("msg : ", self.msg)
        print("------------------------")
        
myTest = MyTest("방실이", "안녕하세요")
myTest.print_test()

 

- self

- 클래스 인스턴스

class Foo :
  def function01(self) :
    print("function01" , id(self))
  def function02() :
    print("function02")
    
foo = Foo()
foo.function01()
# self 인자는 파이썬이 자동으로 넘겨준다.

foo.function02()
# TypeError: function02() takes 0 positional arguments but 1 was given

id(foo)
# foo.function01() 의 id(self) 와 동일하다.

Foo.function01()
# TypeError: function01() missing 1 required positional argument: 'self'

foo1 = Foo()
Foo.function01(foo1)
# function01 2861741202248

id(foo1)
# 2861741202248

 

- 클래스 네임스페이스

- 변수가 객체를 바인딩할 때 그 둘 사이의 관계를 저장하고 있는 공간

class Test :
  name = "홍길동"
    
# 네임스페이스 확인
dir()

# Test 클래스 네임스페이스
Test.__dict__

# 별도의 인스턴스 생성
t01 = Test()
t02 = Test()

t01.name = "방실이"

Test.name
t01.name
t02.name

 

- 클래스 변수와 인스턴스 변수

class Vari :
  # 클래스 변수
  num = 0 
  def __init__(self, name) :
    # 인스턴스 변수
    self.name = name 
    Vari.num += 1
  def __del__(self) :
    Vari.num -= 1

# 두개의 개별 인스턴스
kim = Vari("kim")
park = Vari("Park")

kim.name
park.name

# 두개의 개별 인스턴지만, num 클래스 변수이다.
kim.num
park.num

 

- 클래스 상속

class Parent :
  def hello(self) :
    print("parent hello")

par = Parent()
par.hello()

class Child(Parent) :
  def msg(self) :
    print("child msg~~~")

child1 = Child()
child1.hello()
child1.msg()

 

반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

1. 함수

- def 키워드 / 함수 정의

def print_name( n , str ) :
	for i in range(n) :
		print( str )

print_name( 1 , "hello world~!" )

 

- return / 반환 / 두개의 값 반환은 튜플을 사용

def plus( x , y ) :
	return x + y

plus( 1 , 5 )
print(plus( 1 , 5 ))
def plus_minus( x , y ) :
	p = x + y
	m = x - y
	return ( p , m )

plus_minus( 1 , 3 )
print(plus_minus( 1 , 3 ))
print(plus_minus( 1 , 3 )[0])
print(plus_minus( 1 , 3 )[1])

( p , m ) = plus_minus( 1 , 3 )
p # 4
m # -2

 

2. 모듈

- 프로그램이나 하드웨어 기능의 단위

- 파이썬은 파일 단위로 작성된 파이썬 코드를 모듈이라고 부름

- spyder 환경에서 위에 작성한 코드를 hello.py 이름으로 파일을 저장한다.

 

 

- 파이썬 __name__ 변수

- 파일에서 실행시에는 __main__ 이라는 문자열 바인딩

- import hello 시에는 파일명인 hello 문자열 바인딩

hello.py

def print_name( n , str ) :
	for i in range(n) :
		print( str )

def plus( x , y ) :
	return x + y

def plus_minus( x , y ) :
	p = x + y
	m = x - y
	return ( p , m )


print(__name__)

if( __name__ == "__main__" ) :
    print( print_name(2, "hello~!!!!!!") )

 

- import / hello / time / type(_) / dir()

- hello : 내가 만든 py 파일

- time : 파이썬 자체 모듈

- type(_) : 최근 반환값의 타입

- dir() : 모듈 안의 함수 / 변수 확인

import hello, time

hello.print_name(3, "hello~~~!!")
hello.plus(4,5)
hello.plus_minus(5,5)

time.time()
time.sleep(1) # 1초

# 최근 반환값의 타입
type(_)

# 모듈 / 파일 위치
import random
random
# <module 'random' from 'C:\\Users\\User\\Anaconda3\\lib\\random.py'>

# 모듈 안의 함수 / 변수 확인
dir(random)

 

- os 모듈

import os
os
dir(os)

# 현재경로
os.getcwd()

# 파일과 디렉토리 목록 리스트
# os 파일경로의 파일과 디렉토리
os.listdir()

# 해당경로의 파일과 디렉토리
os.listdir("C://")

files = os.listdir("C://")
len(files)
type(files)

for x in os.listdir("C:\\Users\\User\\Anaconda3") :
  if x.endswith("exe") :
  	print(x)

 

- import 의 3가지 방법

- import os / from os import listdir / import os as winos

- os 모듈 임포트 / os 모듈로부터 listdir 을 임포트 / os 모듈을 winos 로 임포트

 

- 내장함수(Built-in Functions)

abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round() delattr()
hash() memoryview() set()    

 

# 절대값 반환
abs(-3)

# 문자열 반환
chr(97)

# 리스트, 튜플, 문자열 enumerate 객체 반환
for i, name in enumerate(["000", "111", "222"]) :
	print( i , name )

# 길이 , 원소개수
len([1,2,3,4])

# 리스트 반환
list("hello")
list((1,2,3))

# 최대값
max(1,2,3,4,5)
max([4,3])

# 최소값
min(1,2,3,4,5)
min([4,3])

# 정렬
sorted([3,4,2,0])

# 정수 반환
int("3")

# 문자열 반환
str(3)

 

반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

1. Boolean

- True / False 파이썬의 예약어로 첫 글자를 대문자로 사용한다.

a = True
type(a)

 

- 파이썬 비교 연산자

연산자 연산자 의미
== 같다.
!= 다르다.
> 크다.
< 작다.
>= 크거나 같다.
<= 작거나 같다.
test = "test01"
test == "test01"

 

2. 논리 연산자

- and , or , not

- 그리고 , 또는 , ~ 아닌

True and False
True or False
not False

 

3. if 문 ( 조건문 )

- 들여쓰기 주의할 것

cnt = 0
if cnt > 0 :
	print( "cnt 가 0 보다 크면" )
elif cnt < 0 :
	print( "cnt 가 0 보다 작으면" )
else :
	print( "그렇지 않으면 0 이랑 같다." )

 

4. for 문 ( 반복문 )

for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
	print(i)

 

- range

- 범위

range(0, 11)
list(range(0, 11))
for i in range(0, 11) :
	print(i)

 

- for 와 튜플

- 튜플은 수정할 수 없기 때문에 리스트보다 빠르다함.

tu = ( "tu01", "tu02", "tu03" )
for tmp in tu :
	print( tmp )

 

- for 와 딕셔너리

- 딕셔너리는 키-값 쌍을 저장하는 구조이다.

dic = { "dic01" : 100, "dic02" : 200, "dic03" : 300 }
for key, val in dic.items() :
	print( key, val )

for key in dic.keys() :
	print( key, dic[key] )

 

5. while 문 ( 반복문 )

i = 0
while i <= 5 :
	print(i)
	i = i + 1

 

- while 과 if

num = 0
while num <= 10 :
	if num % 2 == 1 :
		print(num)
	num += 1

 

- break 와 continue

- 무한루프

- Ctrl + C 를 눌러서 멈춘다.

num = 0
while 1 :
	print(1)

 

- break

- 멈춰

num = 0
while 1 :
	print(1)
	break

while 1 :
	print(num)
	if num == 10 :
		break
	num += 1

 

- continue

- 계속

num = 0
while num < 10 :
	num += 1
	if num == 5 :
		continue
	print(num)

 

6. 중첩루프

- pass 키워드는 아무것도 수행하지 않음을 의미

for i in [1, 2, 3, 4] :
	for j in [1, 2, 3, 4] :
		pass

- 2차 구조

num = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]]
num[0]
type(num[0])

num[0][0]
num[1][0]

for first in num :
	for second in first :
		print( second )
반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

- 기본자료구조

- 리스트 / 튜플 / 딕셔너리

- list / tuple / dictionary

 

1. 리스트 ( list )

list01 = [ '아이템01' , '아이템02' , '아이템03', '아이템04', '아이템05' ]

 

- 리스트 인덱싱

list01[0]
list01[1]
list01[2]
list01[-1]
list01[-2]
list01[-3]

 

- 리스트 슬라이싱

list01[0:2]
list01[2:4]
list01[:-3]

 

- 리스트 데이터 삽입

list01.append('아이템06')
list01.insert( 2 , '중간아이템01' )

 

- 리스트 데이터 삭제

len(list01)
list01[2]
del list01[2]

 

 

2. 튜플 ( tuple )

t = ('아이템01', '아이템02', '아이템03', '아이템04', '아이템05')

 

- 튜플의 접근

len(t)
t[0]
t[1]
t[2]

 

- 튜플 슬라이싱

t[0:2]

 

- 튜플과 리스트의 차이점

- 리스트는 [] 사용 , 튜플은 () 사용

- 리스트는 원소를 변경할 수 있지만, 튜플은 변경할 수 없다.

list01 = [1,2,3,4]
list01[0] = 6
t[0] = 'x'
// TypeError: 'tuple' object does not support item assignment

 

 

3. 딕셔너리 ( dict )

dic = {}
type(dic)
dic= {'a':100 , 'b':200 }

 

- 딕셔너리 데이터 삽입

dic['c'] = 300
dic

 

- 딕셔너리 데이터 삭제

dic['a']
del dic['a']
dic

 

- 딕셔너리 키-값구하기

dic.keys()
dic.values()

 

- dic.keys() / dic.values() 반환값이 리스트가 아니므로, list 키워드로 타입을 변환한다.

- list 라는 이름으로 변수를 선언해두면 에러나니, 변수선언에 신중하자. ( TypeError: 'list' object is not callable )

keyList = list( dic.keys() )
valueList = list( dic.values() )

 

- 키값 확인 ( 존재여부 )

'c' in dic.keys()
반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
1. Python 변수/문자열/기본데이터타입  (0) 2020.01.20
Python 시작  (0) 2020.01.14
반응형

1. 변수

x = 100

- x 에 100 의 값을 담다.

- x 에 100 을 바인딩한다.

 

- id 함수

- 메모리에 할당된 주소를 확인 할 수 있다.

x = 100
id(x)

 

2. 문자열(String)

- '' (작은따옴표) , ""(큰따옴표) 로 묶인 문자의 모임

str = "hello"
str = 'hello world'

 

- 문자열 길이 ( len )

str = 'hello world'
len(str)

 

- 문자열 자르기 ( slice )

str[0:5]
str[:5]
str[6:]
str[:-6]

 

- 문자열 분리 ( split )

str.split(" ")
str.split(" ")[0]
str.split(" ")[1]

 

- 문자열 합치기 (+)

str01 = 'hi'
str02 = 'Python'
str01 + '! ' + str02
'hi! Python'

 

3. 기본데이터타입

- 정수, 실수, 문자열

- int , float , str

type(1000)
type(3.141)
type('Python')

 

반응형

'IT > Python' 카테고리의 다른 글

Python PyQt5 QAxContainer import 에러  (0) 2020.05.18
Python / GUI  (0) 2020.05.14
Python / COM  (0) 2020.05.13
7. Python IDE  (0) 2020.02.07
6. Python 파일읽기 / 쓰기  (0) 2020.02.05
5. Python 클래스  (0) 2020.02.04
4. Python 함수와 모듈  (0) 2020.02.04
3. Python 제어문  (0) 2020.01.29
2. Python 기본자료구조(리스트/튜플/딕셔너리)  (0) 2020.01.20
Python 시작  (0) 2020.01.14

+ Recent posts