[파이썬 제4강] Lists
sources :
https://www.kaggle.com/code/colinmorris/lists
Lists
Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources
www.kaggle.com
Lists
Lists in Python represent ordered sequences of values. Here is an example of how to create them:
리스트는 파이썬을 대표하는 값의 순서쌍이다. 여기에 예시를 보였다.
We can put other types of things in lists:
우리는 숫자 뿐만 아닌 다른 값들도 리스트로 만들 수 있다.
We can even make a list of lists:
심지어 리스트로된 리스트도 가능하다.
...
A list can contain a mix of different types of variables:
또한 리스트에는 서로 다른 타입의 값들도 혼용해서 넣을 수 있다.
Indexing
인덱싱 ~ 위치찾기
You can access individual list elements with square brackets.
리스트를 구성하는 각 요소는 [ ] 을 이용하여 접근할 수 있다.
Which planet is closest to the sun? Python uses zero-based indexing, so the first element has index 0.
(앞에 만든 행성 리스트에서) 태양에 가장 가까운 행성은? 파이썬의 인덱싱은 0부터 시작하기 때문에 가장 planets[0]에서 얻을 수 있다.
Elements at the end of the list can be accessed with negative numbers, starting from -1:
[ ]안에 음수를 넣을 수도 있는데, 리스트는 가장 마지막 요소를 인덱스 -1로 조회할 수 있다. 즉, 끝에서 첫번째는 [-1] , 끝에서 두번째는 [-2], ..., 이런식으로.
What are the first three planets? We can answer this question using slicing:
첫 3개의 행성은 무엇인가? 즉 앞에서 3번째까지의 행성은 무엇무엇인가? 이렇게 묻는다면 우리는 슬라이싱이라는 기법을 이용해야 한다.
이것은 리스트의 구성요소중 일부를 원하는 만큼 잘라서 표현해주는 기법이다. (인덱싱; 한개, 슬라이싱: 하나이상)
아래 예시로 planets[0:3]
을 하면, ['Mercury', 'Venus', 'Earth'] 가 표현된다.
planets[0:3] is our way of asking for the elements of planets starting from index 0 and continuing up to but not including index 3.
planests[0:3]은 인덱스 0 TO 3 인데, 3을 포함하지는 않는다. 즉 0=< index <3 이되는데,
The starting and ending indices are both optional. If I leave out the start index, it's assumed to be 0. So I could rewrite the expression above as:
시작과 끝 인덱스를 쓰지 않게 되면 , 예를 들어,
planets[:3]은 인덱스가 'to 3 ' 여전히 3은 포함하지 않는다.
planets[3:]은 인덱스가 3 ~ 로 3을 포함한다.
각 결과를 참고해라.
또 음수인 인덱스를 활용해 보면
We can also use negative indices when slicing:
# All the planets except the first and last
planets[1:-1]
['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']
# The last 3 planets
planets[-3:]
['Saturn', 'Uranus', 'Neptune']
#음수를 사용하면 말이 쉽지 헷갈리기 쉽상이다. 가능한 사용하지 않는 것을 추천한다.
Changing lists
Lists are "mutable", meaning they can be modified "in place".
리스트는 요소를 수정할수 있다.
One way to modify a list is to assign to an index or slice expression.
한가지 수정 방법은 해당 인덱스 또는 슬라이싱된 리스트에 새로운 값을 넣는 것이다.
For example, let's say we want to rename Mars:
예를 들어, Mars 대신에 'Malacandra'를 넣으면,
>>
planets[3] = 'Malacandra'
planets
['Mercury',
'Venus',
'Earth',
'Malacandra',
'Jupiter',
'Saturn',
'Uranus',
'Neptune']
Hm, that's quite a mouthful. Let's compensate by shortening the names of the first 3 planets.
또는 첫 3행성의 이름을 약자로 써보면
>>
planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets)
# That was silly. Let's give them back their old names
하지만 약자로 쓴게 너무 없어 보이니 원래대로 돌리자면,
>>
planets[:4] = ['Mercury', 'Venus', 'Earth', 'Mars',]
List functions
Python has several useful functions for working with lists.
파이썬은 리스트에 사용할 수 있는 다양한 함수들이 있다.
1) len
len gives the length of a list:
len은 리스트의 길이를 반환
# How many planets are there?
len(planets)
8
sorted returns a sorted version of a list:
sorted는 리스트의 요소를 정렬한다.
예를 들면 행성이름을 알파벳순으로 정리하려면,
>>
sorted(planets)
We've previously used the min and max to get the minimum or maximum of several arguments. But we can also pass in a single list argument.
앞서서 리스트에 min이나 max 함수를 써왔다.
혹은 아래와 같이 작성한다.
>>
max(primes)
Interlude: objects
I've used the term 'object' a lot so far - you may have even read that everything in Python is an object. What does that mean?
나는 앞서 객체(object)라는 말을 오랫동안 사용했는데, 파이썬을 구성하고 있는 모든 것은 이러한 객체로 이루어져 있다.
In short, objects carry some things around with them. You access that stuff using Python's dot syntax.
간단히 이야기하자면 오브젝트는 자신의 주변에 뭔가를 왕창 댓구 살고 있는 거고, 당신은 그것들에 python dot syntax 를 가지고 접근할 수 있는 것이다.
For example, numbers in Python carry around an associated variable called imag representing their imaginary part. (You'll probably never need to use this unless you're doing some very weird math.)
예를 들어, 파이썬은 변수의 (숫자)허수부를 접근하기 위해 dot를 사용한다.
>>
x = 12
# x is a real number, so its imaginary part is 0.
print(x.imag)
# Here's how to make a complex number, in case you've ever been curious:
c = 12 + 3j
print(c.imag)
0
3.0
The things an object carries around can also include functions. A function attached to an object is called a method. (Non-function things attached to an object, such as imag, are called attributes).
객체에 붙는 함수를 메소드(method)라고 한다.
For example, numbers have a method called bit_length. Again, we access it using dot syntax:
예를 들어, 어떤 숫자가(숫자도 객체의 일종) bit_length라는 메소드를 가지고 있다면, dot(점)을 찍어서 그 메소드를 사용할 수 있다는 것이다.
x.bit_length
<function int.bit_length()>
To actually call it, we add parentheses:
정말 함수를 호출하려면 우리는 괄호를 붙여야 한다.
x.bit_length()
Aside: You've actually been calling methods already if you've been doing the exercises. In the exercise notebooks q1, q2, q3, etc. are all objects which have methods called check, hint, and solution.
참고로 이미 앞선 강좌의 excercise에서 q1.~ q2.~, q3.~ 등의 객체에서 check(), hint(), solution() 의 메소드를 사용하는 것을 이미 봤다.
In the same way that we can pass functions to the help function (e.g. help(max)), we can also pass in methods:
앞에서 help() 함수로 function 정보를 안 것과 같이 메소드 형태를 help에 넣어도 된다.
>>
help(x.bit_length)
Help on built-in function bit_length:
bit_length() method of builtins.int instance
Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
The examples above were utterly obscure. None of the types of objects we've looked at so far (numbers, functions, booleans) have attributes or methods you're likely ever to use.
위에서 보여준 예시는 별 의미가 없긴하다. 여태 우리가 다뤄본 숫자나 함수, 논리값등은 쓸만한 속성값(attributes)이나 메소드(methods)를 가지고 있지는 않다.
But it turns out that lists have several methods which you'll use all the time.
하지만 리스트가 다양한 메소드를 가지고 있다는 점을 알았을 것이다. 아래에 몇가지를 나열하자면
List methods
list.append modifies a list by adding an item to the end:
list.append()는 리스트 끝에 아이템을 더할때 사용
Why does the cell above have no output? Let's check the documentation by calling
왜 아무 출력값이 없는가? help를 이용해서 체크해보자.
>>
help(planets.append).
Aside: append is a method carried around by all objects of type list, not just planets, so we also could have called help(list.append). However, if we try to call help(append), Python will complain that no variable exists called "append". The "append" name only exists within lists - it doesn't exist as a standalone name like builtin functions such as max or len.
참고로 ... help(append)만 호출하면 에러가 난다. append는 독립적으로 존재하는 함수가 아니기 때문이다.
The -> None part is telling us that list.append doesn't return anything.
아무튼 help()를 통해 append가 리턴값이 없다는 것을 알 수 있다.
But if we check the value of planets, we can see that the method call modified the value of planets:
하지만, planets 리스트를 확인해보면
...
list.pop removes and returns the last element of a list:
list.pop()은 리스트의 마지막 요소를 제거한다.
Searching lists
Where does Earth fall in the order of planets? We can get its index using the list.index method.
Earth가 planets 리스트에서 몇번째인지 어떻게 알 수 있나? 우리는 이 요소(earth)가 갖는 인덱스 값을 list.index() 메소드로 알 수 있다.
>>
planets.index('Earth')
2
It comes third (i.e. at index 2 - 0 indexing!).
인덱스값이 2니까 3번째이다. (0,1,2)
...
To avoid unpleasant surprises like this, we can use the in operator to determine whether a list contains a particular value:
이런 오류를 방지하기 위해 우리는 'in' 연산자를 이용해서 리스트안에 있는 값 만을 억세스할 수도 있다.
>>
# Is Earth a planet?
"Earth" in planets
True
>>
# Is Calbefraques a planet?
"Calbefraques" in planets
False
There are a few more interesting list methods we haven't covered. If you want to learn about all the methods and attributes attached to a particular object, we can call help() on the object itself. For example, help(planets) will tell us about all the list methods:
리스트에는 이외에도 많은 메소드들이 있지만 여기서 모두 다룰 수는 없다. ... help에 객체를 넣어보면 메소드 리스트를 얻을 수 있다.
Tuples
튜플
Tuples are almost exactly the same as lists. They differ in just two ways.
튜플은 리스트와 거의 유사하지만 2가지 측면에서 다르다.
1: The syntax for creating them uses parentheses instead of square brackets
우선 생성할때 [ ] 대괄호 대신에 () 괄호를 사용한다.
2: They cannot be modified (they are immutable).
일단 생성된 튜플은 수정이 안된다.
For example, the as_integer_ratio() method of float objects returns a numerator and a denominator in the form of a tuple:
부동소수에서 as_integer_ratio() 는 분자와 분모를 튜플형태로 돌려준다.
>>
x = 0.125
x.as_integer_ratio()
(1, 8)
These multiple return values can be individually assigned as follows:
이런 튜플은 다음과 같이 입력 시킬 수 있다.
>>
numerator, denominator = x.as_integer_ratio()
>>
print(numerator / denominator)
0.125
================================================
Do Excercise by yourself.