woneuy01 / python2

0 stars 0 forks source link

map filter function #7

Open woneuy01 opened 4 years ago

woneuy01 commented 4 years ago

def doubleStuff(a_list): """ Return a new list in which contains doubles of the elements in a_list. """ new_list = [] for value in a_list: new_elem = 2 * value new_list.append(new_elem) return new_list

things = [2, 5, 9] print(things) things = doubleStuff(things) print(things)


[2, 5, 9] [4, 10, 18]

woneuy01 commented 4 years ago

ef triple(value): return 3*value

def tripleStuff(a_list): new_seq = map(triple, a_list) // map(function, list) 이렇게 쓴다. return list(new_seq)

def quadrupleStuff(a_list): new_seq = map(lambda value: 4*value, a_list) //function 대신에 lambda 를 쓸수 있다. return list(new_seq)

things = [2, 5, 9] things3 = tripleStuff(things) print(things3)

things4 = quadrupleStuff(things) print(things4)


[6, 15, 27] [8, 20, 36]

woneuy01 commented 4 years ago

things = [2, 5, 9]

things4 = map((lambda value: 4*value), things) print(list(things4))

or all on one line

print(list(map((lambda value: 5*value), [1, 2, 3])))


[8, 20, 36] [5, 10, 15]

woneuy01 commented 4 years ago

lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]

def doubled(val): return val*2

greeting_doubled=map(doubled, lst) print(greeting_doubled)


[['hi', 'bye', 'hi', 'bye'], 'hellohello', 'goodbyegoodbye', [9, 2, 9, 2], 8]

woneuy01 commented 4 years ago

abbrevs = ["usa", "esp", "chn", "jpn", "mex", "can", "rus", "rsa", "jam"]

def uppered(val): return val.upper()

abbrevs_upper=map(uppered, abbrevs)

abbrevs_upper1=map(lambda x: x.upper(), abbrevs) // 위와 같이 두가지 다 가능하다.

print(abbrevs_upper) print(abbrevs_upper1)


['USA', 'ESP', 'CHN', 'JPN', 'MEX', 'CAN', 'RUS', 'RSA', 'JAM'] ['USA', 'ESP', 'CHN', 'JPN', 'MEX', 'CAN', 'RUS', 'RSA', 'JAM']

woneuy01 commented 4 years ago

def keep_evens(nums): new_list = [] for num in nums: if num % 2 == 0: new_list.append(num) return new_list

print(keep_evens([3, 4, 6, 7, 0, 1]))


[4, 6, 0]

woneuy01 commented 4 years ago

def keep_evens(nums): new_seq = filter(lambda num: num % 2 == 0, nums) return list(new_seq)

print(keep_evens([3, 4, 6, 7, 0, 1]))


[4, 6, 0]

woneuy01 commented 4 years ago
  1. Write code to assign to the variable filter_testing all the elements in lst_check that have a w in them using filter.

lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']

filter_testing=filter(lambda x: 'w' in x, lst_check)


lst = ["witch", "halloween", "pumpkin", "cat", "candy", "wagon", "moon"]

lst2 = filter(lambda x: 'o' in x, lst)