Python's some single-line code (excerpt)

Source: Internet
Author: User

1. Multiply each element in the list by 2

Print map (Lambda x:x * 2, Range (1,11))

2, the sum of all the elements in the list

Print sum (range (1,1001))

3. Determine if there are certain words in a string

Wordlist = ["Scala", "Akka", "Play Framework", "SBT", "Typesafe"]

Tweet = "This is a example tweet talking about Scala and SBT."

Print map (lambda x:x in Tweet.split (), wordlist)

4. Read the file

Print open ("ten_one_liners.py"). ReadLines ()

5, wish you a happy birthday!

Print map (lambda x: "Happy Birthday to" + ("You" if x! = 2 Else "Dear Name"), Range (4))

6. Filter the values in the list

Print reduce (lambda (A, B), C: (a+[c],b) If C >-Else (A, B + [C]), [49, 58, 76, 82, 88, 90], ([],[]))

7. Get the XML Web service data and analyze

From Xml.dom.minidom import Parse, parsestringimport urllib2# Note that I converted it to XML format and printed it out in print parse (Urllib2.urlopen ("http:/ /search.twitter.com/search.atom?&q=python ")). Toprettyxml (encoding=" Utf-8 ")

8. Find the smallest or largest number in the list

Print min ([7,, 98]) print Max ([14, 35,-7, 46, 98])

9. Parallel processing

Import Multiprocessingimport Math

Print List (multiprocessing. Pool (processes=4). Map (Math.exp,range (1,11)))

"Sieve of Eratosthenes" algorithm

Python does not have the sieve of Eratosthenes operator, but it is not difficult for python.

n = # We want to find prime numbers between 2 and 50print sorted (set (range (2,n+1)). Difference (Set ((P * f) as P in rang E (2,int (n**0.5) + 2) for F in range (2, (n/p) +1))))

Python's some single-line code (excerpt)

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.