티스토리 뷰

IT/Python: Codecademy

5 Lists & Dictionaries

Last72 2018. 2. 22. 22:35
Cut List
1
2
3
4
5
6
7
8
9
10
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
 
# The first and second items (index zero and one)
first = suitcase[0:2]
 
# Third and fourth items (index two and three)
middle = suitcase[2:4]
 
# The last two items (index four and five)
last =  suitcase[4:6]

Cut string
1
2
3
4
5
6
7
8
9
10
animals = "catdogfrog"
 
# The first three characters of animals
cat = animals[:3]
 
# The fourth through sixth characters
dog = animals[3:6]
 
# From the seventh character to the end
frog = animals[6:]

Add dictionary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
inventory = {
  'gold' : 500,
  'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
  'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}
 
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
 
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
 
# Your code here
 
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['backpack'].remove('dagger')
inventory['backpack'].sort()
inventory['gold'] += 50
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# key - animal_name : value - location
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines
 
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
 
# Your code here!
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
 
zoo_animals['Rockhopper Penguin'] = 'Arctical Exhibit'
 
print zoo_animals


for loop with if statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
shopping_list = ["banana", "orange", "apple"]
 
stock = {
  "banana": 6,
  "apple": 0,
  "orange": 32,
  "pear": 15
}
     
prices = {
  "banana": 4,
  "apple": 2,
  "orange": 1.5,
  "pear": 3
}
 
# Write your code below!
def compute_bill(food):
  total = 0
  for item in food:
    if stock[item] > 0:
      total += prices[item]
      stock[item] -= 1
  return total
 
print compute_bill(shopping_list)

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

7 Lists and Functions  (0) 2018.02.26
6 Student Becomes the Teacher  (0) 2018.02.24
Python 4 Functions  (0) 2018.02.21
Python 3 Conditionals and Control Flow  (0) 2018.02.21
Python 2 Strings and Console Output  (0) 2018.02.18
댓글
Announcement
Recent Posts
Recent Comments
Total
Today
Yesterday
Link
TAG
more
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Search by month