[codecademy] 5.LISTS & DICTIONARIES

Posted by 알 수 없는 사용자
2015. 8. 28. 08:19 프로그래밍/Python

LISTS & DICTIONARIES

Python Lists and Dictionaries 1/14

Introduction to Lists

List는 여러가지 데이터조각들을 모아놓은 데이터타입의 종류이다.

List이름 = [item1, item2] 와같은 형식으로 정의한다.

문제

The list zoo_animals has three items (check them out on line 1). 

Go ahead and add a fourth! Just enter the name of your favorite animal (as a "string") on line 1, after the final comma but before the closing ].

Python Lists and Dictionaries 2/14

Access by Index

List에 저장되어있는 값들을 사용하기 위해서는 인덱스라는것을 통하여 가능하다.( ex> list_name[index] )

인덱스는 0번부터 시작한다.(리스트의 첫번째 값이 1번이아닌 0번으로 지정된다.)

문제

Write a statement that prints the result of adding the second and fourth items of the list. Make sure to access the list by index!

Python Lists and Dictionaries 3/14

New Neighbors

리스트의 인덱스 값을 통하여 리스트에 새로운값을 저장할수있다.

zoo_animals[2] = "hyena" 라고 값을 저장하였을때 이미 2번인덱스에 값이 저장되어있더라도 2번인덱스와 그뒷번 인덱스의 값들이 

자동으로 하나씩 밀려서 저장된다.

문제

Write an assignment statement that will replace the item that currently holds the value "tiger" with another animal (as a string). It can be any animal you like.

Python Lists and Dictionaries 4/14

Late Arrivals & List Length

리스트의 길이는 가변적이다 . 만약 3개의 item이 저장되어있는 리스트( 길이 = 3 )에 새로운 item을 저장하게되면 길이가 4로 늘어난다.

list_name.append('x')를 사용하면 인덱스에 관계없이 가장 뒤쪽에 x라는 item이 하나 추가된다.

문제

01. On lines 5, 6, and 7, append three more items to the suitcase list, just like the second line of the example above. (Maybe bring a bathing suit?)

02. Then, set list_length equal to the length of the suitcase list.

Python Lists and Dictionaries 5/14

List Slicing

리스트의 인덱스를 이용하여 리스트의 특정 부분을 참조할수 있다.

slice = letters[1:3] -> letter 리스트에서 1번인덱스 부터 3번인덱스 까지 ( 1<= slice < 3) slice에 저장한다.

문제

01. On line 4, create a list called middle containing only the two middle items from suitcase.

02. On line 5, create a list called last made up only of the last two items from suitcase.

Python Lists and Dictionaries 6/14

Slicing Lists and Strings

문자열도 여러개의 문자가 리스트형태로 저장된 형태이다 , 따라서 리스트와 마찬가지로 특정부분을 참조할수 있다.

또 , list_name[:2] 는 0번인덱스부터 2번까지, list_name[2:] 는 2번부터 마지막인덱스까지 참조된다.

문제

01. Assign to dog a slice of animals from index 3 up until but not including index 6.

02. Assign to frog a slice of animals from index 6 until the end of the string.

Python Lists and Dictionaries 7/14

Maintaining Order

리스트내에서 특정한 값의 인덱스를 찾아낼수도 있다. list_name.index("x") -> list_name 리스트에서 "x"의 인덱스

또, 특정부분에 값을 삽입할수 있다. list_name.insert(3,"x") -> list_name 리스트의 3번 인덱스에 "x" 값을 삽입.

문제

01. Use the .index(item) function to find the index of "duck". Assign that result to a variable called duck_index.

02. Then .insert(index, item) the string "cobra" at that index.

Python Lists and Dictionaries 8/14

For One and All

리스트에 있는 모든 값을 참조하고 싶을때, for 루프문을 사용하면 된다.

for variable in list_name:

~~~~~

-> list_name 리스트에 있는 모든 값 ( variable 에 저장 )에 대하여 ~~~~를 수행한다.

문제

Write a statement in the indented part of the for-loop that prints a number equal to 2 * number for every list item.

Python Lists and Dictionaries 9/14

More with 'for'

sort() 를 이용하여 리스트내의 값들을 정렬할 수 있다.

list_name.sort() -> list_name 리스트의 값을 알파벳순or오름차순 으로 정렬한다.(알파벳과 숫자가 같이 있을경우 숫자먼저)

문제

01. Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list.

02. Then sort square_list!

Python Lists and Dictionaries 10/14

This Next Part is Key

dictionary 는 list와 비슷하지만, index값이 아닌 key값으로 값을 참조한다. key 값은 문자열이나 숫자 모두 가능하다.

dic = {'key1' : 1,'key2' : 2} -> dic이라는 dictionary를 선언하고 key1은 1이라는 값을 가리키고, key2는 2라는 값을 가리킨다.

문제

Print the values stored under the 'Sloth' and 'Burmese Python' keys. Accessing dictionary values by key is just like accessing list values by index:

residents['Puffin']

Python Lists and Dictionaries 11/14

New Entries

dictionary 는 list와 마찬가지로 값을 추가할수 있다.

dict_name[new_key] = new_value 

문제

Add at least three more key-value pairs to the menu variable, with the dish name (as a "string") for the key and the price (a float or integer) as the value. Here's an example:

menu['Spam'] = 2.50

Python Lists and Dictionaries 12/14

Changing Your Mind

dictionary의 값을 변경하거나 삭제할수 있다.

del  dict_name[key_name] ->key_name에 해당되는 값을 삭제한다.

dict_name[key] = new_value -> key에 해당하는 값을 new_value로 변경한다.

문제

Delete the 'Sloth' and 'Bengal Tiger' items from zoo_animals using del.


Set the value associated with 'Rockhopper Penguin' to anything other than 'Arctic Exhibit'.

Python Lists and Dictionaries 13/14

Remove a Few Things

list에서도 dictionary의 del 과같이 저장되어있는 값을 삭제할수 있다.

list_name.remove("xxx") -> list_name 리스트에서 "xxx"값을 삭제

문제

Remove 'dagger' from the list of items stored in the backpack variable.

Python Lists and Dictionaries 14/14

It's Dangerous to Go Alone! Take This

복습해보자.

문제

01. Add a key to inventory called 'pocket'

02. Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint'

03. .sort() the items in the list stored under the 'backpack' key

04. Then .remove('dagger') from the list of items stored under the 'backpack' key

05. Add 50 to the number stored under the 'gold' key


A Day at the Supermarket 1/13

BeFOR We Begin
연습을 하기전에 for 루프문을 한번더 복습하고 가자.
for루프문은 list나 dictionary의 가장 작은 인덱스(0번) 부터 가장마지막 인덱스 까지 모두 참조한다.

문제
Use a for loop to print out all of the elements in the list names.



A Day at the Supermarket 1/13
This is KEY!
dictionary도 list와 같이 for 루프문에 사용할수 있다.
dictionary를 for루프문을 통하여 참조하게 되면 특정한 순서없이 참조된다.

문제
Use a for loop to go through the webster dictionary and print out all of the definitions.

A Day at the Supermarket 3/13

Control Flow and Looping
for루프문에서 반복되는 도중에 특정한 item에 특정한 작업?이 필요할때 조건문을 사용한다.

문제
01. Like step 2 above, loop through each item in the list called a.
02. Like step 3 above, if the number is even, print it out. You can test if the item % 2 == 0 to help you out.


A Day at the Supermarket 4/13

Lists + Functions
함수에서도 list형태의 값을 매개변수로 입력받거나 반환할수 있다.

문제
Write a function that counts how many times the string "fizz" appears in a list.

01. Write a function called fizz_count that takes a list x as input.
02. Create a variable count to hold the ongoing count. Initialize it to zero.
03. for each item in x:, if that item is equal to the string "fizz" then increment the count variable.
04. After the loop, please return the count variable.
05. For example, fizz_count(["fizz","cat","fizz"]) should return 2.


A Day at the Supermarket 5/13

String Looping


문제
Run the code to see string iteration in action!


A Day at the Supermarket 6/13

Your Own Store!
연습 ( supermarket )
dictionary변수 만들기

문제
01. Create a new dictionary called prices using {} format like the example above.
02. Put these values in your prices dictionary, in between the {}:

"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
Yeah, this place is really expensive. (Your supermarket subsidizes the zoo from the last course.)


A Day at the Supermarket 7/13

Investing in Stock
dictionary변수 만들기

문제
Create a stock dictionary with the values below.
"banana": 6
"apple": 0
"orange": 32
"pear": 15

A Day at the Supermarket 8/13

Keeping Track of the Produce
for 루프문 사용하여 dictionary 값 참조하기

문제
01. Loop through each key in prices.
02. Like the example above, for each key, print out the key along with its price and stock information. Print the answer in the following format:
apple
price: 2
stock: 0
Like the example above, because you know that the prices and stock dictionary have the same keys, you can access the stock dictionary while you are looping through prices.

When you're printing, you can use the syntax from the example above.


A Day at the Supermarket 9/13

Something of Value
for 루프문 사용하여 dictionary 값 참조하기

문제
Let's determine how much money you would make if you sold all of your food.

01. Create a variable called total and set it to zero.
02. Loop through the prices dictionaries.
03. For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add 04. it to total.
05. Finally, outside your loop, print total.


A Day at the Supermarket 10/13

Shopping at the Market
list변수 만들기

문제
First, make a list called groceries with the values "banana","orange", and "apple".



A Day at the Supermarket 11/13

Making a Purchase
list,dictionary를 사용하는 함수 작성

문제
01. Define a function compute_bill that takes one argument food as input.
02. In the function, create a variable total with an initial value of zero.
03. For each item in the food list, add the price of that item to total.
04. Finally, return the total.
Ignore whether or not the item you're billing for is in stock.

Note that your function should work for any food list.


A Day at the Supermarket 12/13

Stocking Out
list,dictionary를 사용하는 함수 작성

문제
Make the following changes to your compute_bill function:

While you loop through each item of food, only add the price of the item to total if the item's stock count is greater than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count.


A Day at the Supermarket 13/13

Let's Check Out!

문제
Click Save & Submit Code to finish this course.