10 minutes a day, 12 days Getting Started Python (four)

Source: Internet
Author: User

map()The function receives two parameters, one is a function, the other is a sequence, map Functions the passed-in function sequentially to each element of the sequence and returns the result as a new list.


defNum(x):
ReturnX*X

PrintMap(num,[1,2,3,4,5,6,7,8,9])

# [1, 4, 9, +, A, $, +,--]

reduce()A function that acts on a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:


def add (x, y) :
   return x+ y

print reduce (Add,[1 , 3 , 5 , 7 , 9 ])

#25


defList2num(x, Y):
ReturnX*Ten+Y

PrintReduce(list2num,[1,3,5,7,9])

#13579

sorted()The function can sort the list:


PrintSorted([3,6,8,9,4,1,2])
#[1, 2, 3, 4, 6, 8, 9]

defreversed_cmp(x, Y):
IfX>Y:
Return-1
Else:
Return1
return0

PrintSorted([3,6,8,9,4,1,2],REVERSED_CMP)
# [9, 8, 6, 4, 3, 2, 1]

The python closures are similar to those in javascript:


defLazy_sum(*Args:
defs():
Returnsum([x forXinchArgs])
returnS

F= Lazy_sum (1,2,3,4,5)

PrintF ()
# 15
F2= Lazy_sum ()

PrintF2 ()
# 0

Implementing anonymous functions via lambda:


F = lambda x: x*x

print F (5)
# 25

10 minutes a day, 12 days Getting Started Python (four)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.