woneuy01 / python2

0 stars 0 forks source link

sort, sorted #5

Open woneuy01 opened 4 years ago

woneuy01 commented 4 years ago

L1 = [1, 7, 4, -2, 3] L2 = ["Cherry", "Apple", "Blueberry"]

L1.sort() print(L1) L2.sort() print(L2)


[-2, 1, 3, 4, 7] ['Apple', 'Blueberry', 'Cherry']

woneuy01 commented 4 years ago

More importantly, sorted does not change the original list. Instead, it returns a new list.

L2 = ["Cherry", "Apple", "Blueberry"]

L3 = sorted(L2) print(L3) print(sorted(L2)) print(L2) # unchanged

print("----")

L2.sort() print(L2) print(L2.sort()) #return value is None


['Apple', 'Blueberry', 'Cherry'] ['Apple', 'Blueberry', 'Cherry'] ['Cherry', 'Apple', 'Blueberry']


['Apple', 'Blueberry', 'Cherry'] None

woneuy01 commented 4 years ago

L2 = ["Cherry", "Apple", "Blueberry"] print(sorted(L2, reverse=True))


['Cherry', 'Blueberry', 'Apple']

woneuy01 commented 4 years ago

L1 = [1, 7, 4, -2, 3]

def absolute(x): if x >= 0: return x else: return -x

print(absolute(3)) print(absolute(-119))

for y in L1: print(absolute(y))


13 print(absolute(y)) 14 ​

3 119 1 7 4 2 3

woneuy01 commented 4 years ago

Optional Key parameter

L1 = [1, 7, 4, -2, 3]

def absolute(x): if x >= 0: return x else: return -x

L2 = sorted(L1, key=absolute) print(L2)

or in reverse order

print(sorted(L1, reverse=True, key=absolute))


[1, -2, 3, 4, 7] [7, 4, 3, -2, 1]

woneuy01 commented 4 years ago

L1 = [1, 7, 4, -2, 3]

def absolute(x): print("--- figuring out what to write on the post-it note for " + str(x)) if x >= 0: return x else: return -x

print("About to call sorted") L2 = sorted(L1, key=absolute) print("Finished execution of sorted") print(L2)


About to call sorted --- figuring out what to write on the post-it note for 1 --- figuring out what to write on the post-it note for 7 --- figuring out what to write on the post-it note for 4 --- figuring out what to write on the post-it note for -2 --- figuring out what to write on the post-it note for 3 Finished execution of sorted [1, -2, 3, 4, 7]

woneuy01 commented 4 years ago

ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']

def second_let(str): return str[1]

sorted_by_second_let=sorted(ex_lst, key=second_let)

woneuy01 commented 4 years ago

nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16']

def last_char(num): return num[-1] //마지막 숫자를 가져온다

nums_sorted =sorted(nums, reverse=True, key=last_char) //마지막 숫자를 역방향 sort


lambda 이용하는 방법

nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16']

nums_sorted_lambda = sorted(nums, reverse=True, key=lambda num : num[-1])

woneuy01 commented 4 years ago

L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D']

d = {} for x in L: if x in d: d[x] = d[x] + 1 else: d[x] = 1 for x in d.keys(): print("{} appears {} times".format(x, d[x]))


E appears 2 times F appears 1 times B appears 2 times A appears 2 times D appears 4 times I appears 2 times C appears 1 times

woneuy01 commented 4 years ago

L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D']

d = {} for x in L: if x in d: d[x] = d[x] + 1 else: d[x] = 1 y = sorted(d.keys()) for k in y: print("{} appears {} times".format(k, d[k]))


A appears 2 times B appears 2 times C appears 1 times D appears 4 times E appears 2 times F appears 1 times I appears 2 times

woneuy01 commented 4 years ago

L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D']

d = {} for x in L: if x in d: d[x] = d[x] + 1 else: d[x] = 1

y = sorted(d.keys(), key=lambda k: d[k], reverse=True) // d.value()값으로 정렬 for k in y: print("{} appears {} times".format(k, d[k]))


D appears 4 times I appears 2 times A appears 2 times B appears 2 times E appears 2 times C appears 1 times F appears 1 times

woneuy01 commented 4 years ago

L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D']

d = {} for x in L: if x in d: d[x] = d[x] + 1 else: d[x] = 1

def g(k): return d[k]

y =(sorted(d.keys(), key=g, reverse=True)) // value값으로 sort

now loop through the keys

for k in y: print("{} appears {} times".format(k, d[k]))


D appears 4 times I appears 2 times A appears 2 times B appears 2 times E appears 2 times C appears 1 times F appears 1 times

woneuy01 commented 4 years ago

L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D']

d = {} for x in L: if x in d: d[x] = d[x] + 1 else: d[x] = 1

now loop through the sorted keys

for k in sorted(d, key=lambda k: d[k], reverse=True): print("{} appears {} times".format(k, d[k]))


D appears 4 times I appears 2 times A appears 2 times B appears 2 times E appears 2 times C appears 1 times F appears 1 times

woneuy01 commented 4 years ago

sort-4-1: Which of the following will sort the keys of d in ascending order of their values (i.e., from lowest to highest)? L = [4, 5, 1, 0, 3, 8, 8, 2, 1, 0, 3, 3, 4, 3]

d = {} for x in L: if x in d: d[x] = d[x] + 1 else: d[x] = 1

def g(k, d): return d[k]

ks = d.keys()


A. sorted(ks, key=g) XX아님 B. sorted(ks, key=lambda x: g(x, d)) C. sorted(ks, key=lambda x: d[x])

Correct. B. The lambda function takes just one parameter, and calls g with two parameters. C. The lambda function looks up the value of x in d.

woneuy01 commented 4 years ago

dictionary = {"Flowers": 10, 'Trees': 20, 'Chairs': 6, "Firepit": 1, 'Grill': 2, 'Lights': 14}

sorted_keys=sorted(dictionary.keys())

woneuy01 commented 4 years ago

dictionary = {"Flowers": 10, 'Trees': 20, 'Chairs': 6, "Firepit": 1, 'Grill': 2, 'Lights': 14}

sorted_values=sorted(dictionary.keys(), reverse=True, key= lambda x:dictionary[x])

woneuy01 commented 4 years ago

tups = [('A', 3, 2), ('C', 1, 4), ('B', 3, 1), ('A', 2, 4), ('C', 1, 2)] for tup in sorted(tups): print(tup)


('A', 2, 4) ('A', 3, 2) ('B', 3, 1) ('C', 1, 2) ('C', 1, 4)

woneuy01 commented 4 years ago

fruits = ['peach', 'kiwi', 'apple', 'blueberry', 'papaya', 'mango', 'pear'] new_order = sorted(fruits, key=lambda fruit_name: (len(fruit_name), fruit_name)) for fruit in new_order: print(fruit)


kiwi pear apple mango peach papaya blueberry

woneuy01 commented 4 years ago

What would happen though if we wanted to sort it by largest to smallest, and then by alphabetical order?

fruits = ['peach', 'kiwi', 'apple', 'blueberry', 'papaya', 'mango', 'pear'] new_order = sorted(fruits, key=lambda fruit_name: (len(fruit_name), fruit_name), reverse=True) for fruit in new_order: print(fruit)


blueberry papaya peach mango apple pear kiwi

woneuy01 commented 4 years ago

fruits = ['peach', 'kiwi', 'apple', 'blueberry', 'papaya', 'mango', 'pear'] new_order = sorted(fruits, key=lambda fruit_name: (-len(fruit_name), fruit_name)) for fruit in new_order: print(fruit)


blueberry papaya apple mango peach kiwi pear

woneuy01 commented 4 years ago

sort-5-2: What how will the following data be sorted? weather = {'Reykjavik': {'temp':60, 'condition': 'rainy'}, 'Buenos Aires': {'temp': 55, 'condition': 'cloudy'}, 'Cairo': {'temp': 96, 'condition': 'sunny'}, 'Berlin': {'temp': 89, 'condition': 'sunny'}, 'Caloocan': {'temp': 78, 'condition': 'sunny'}}

sorted_weather = sorted(weather, key=lambda w: (w, -weather[w]['temp']), reverse=True)


A. first city name (reverse alphabetically), then temperature (lowest to highest)

woneuy01 commented 4 years ago

states = {"Minnesota": ["St. Paul", "Minneapolis", "Saint Cloud", "Stillwater"], "Michigan": ["Ann Arbor", "Traverse City", "Lansing", "Kalamazoo"], "Washington": ["Seattle", "Tacoma", "Olympia", "Vancouver"]}

print(sorted(states, key=lambda state: len(states[state][0])))


['Washington', 'Minnesota', 'Michigan']

woneuy01 commented 4 years ago

def s_cities_count(city_list): ct = 0 for city in city_list: if city[0] == "S": ct += 1 return ct

states = {"Minnesota": ["St. Paul", "Minneapolis", "Saint Cloud", "Stillwater"], "Michigan": ["Ann Arbor", "Traverse City", "Lansing", "Kalamazoo"], "Washington": ["Seattle", "Tacoma", "Olympia", "Vancouver"]}

print(sorted(states, key=lambda state: s_cities_count(states[state])))


['Michigan', 'Washington', 'Minnesota']

woneuy01 commented 4 years ago

nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] print(nested1[0]) print(len(nested1)) nested1.append(['i']) print("-------") for L in nested1: print(L)


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

['a', 'b', 'c'] ['d', 'e'] ['f', 'g', 'h'] ['i']

woneuy01 commented 4 years ago

nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] y = nested1[1] print(y) print(y[0])

print([10, 20, 30][1]) print(nested1[1][0])


['d', 'e'] d 20 d

woneuy01 commented 4 years ago

def square(x): return x*x

L = [square, abs, lambda x: x+1]

print("names") for f in L: print(f)

print("call each of them") for f in L: print(f(-2))

print("just the first one in the list") print(L[0]) print(L0)


names

> ****call each of them**** 4 2 -1 ****just the first one in the list**** 9
woneuy01 commented 4 years ago

Using indexing, retrieve the string ‘willow’ from the list and assign that to the variable plant.

data = ['bagel', 'cream cheese', 'breakfast', 'grits', 'eggs', 'bacon', [34, 9, 73, []], [['willow', 'birch', 'elm'], 'apple', 'peach', 'cherry']] plant=data[7][0][0]

woneuy01 commented 4 years ago

nested-2-1: Which of the following is a legal assignment statement, after the following code executes? d = {'key1': {'a': 5, 'c': 90, 5: 50}, 'key2':{'b': 3, 'c': "yes"}} A. d[5] = {1: 2, 3: 4} B. d[{1:2, 3:4}] = 5 //dict key immutable 해야함 C. d['key1']['d'] = d['key2'] D. d[key2] = 3

✖️ Incorrect. You gave 4 answers and got 2 correct of 2 needed. 5 is a valid key; {1:2, 3:4} is a dictionary with two keys, and is a valid value to associate with key 5. Dictionary keys must be of immutable types. A dictionary can't be used as a key in a dictionary. d['key2'] is {'b': 3, 'c': "yes"}, a python object. It can be bound to the key 'd' in a dictionary {'a': 5, 'c': 90, 5: 50} key2 is an unbound variable here. d['key2'] would be OK.


✔️Correct. 5 is a valid key; {1:2, 3:4} is a dictionary with two keys, and is a valid value to associate with key 5. d['key2'] is {'b': 3, 'c': "yes"}, a python object. It can be bound to the key 'd' in a dictionary {'a': 5, 'c': 90, 5: 50}

woneuy01 commented 4 years ago

info = {'personal_data': {'name': 'Lauren', 'age': 20, 'major': 'Information Science', 'physical_features': {'color': {'eye': 'blue', 'hair': 'brown'}, 'height': "5'8"} }, 'other': {'favorite_colors': ['purple', 'green', 'blue'], 'interested_in': ['social media', 'intellectual property', 'copyright', 'music', 'books'] } }

color=info['personal_data']['physical_features']['color']