一些精简的 python code
05 Jul 2013Multiple Each Item in a List by 2 print map(lambda x: x * 2, range(1,11))
- Sum a List of Numbers print sum(range(1,1001))
- Verify if Exists in a String wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." print map(lambda x: x in tweet.split(),wordlist)
- Read in a File print open("tenoneliners.py").readlines()
- Happy Birthday to You! print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"),range(4))
- Filter list of numbers print reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[])
- Fetch and Parse an XML web service from xml.dom.minidom import parse, parseString import urllib2 # note - i convert it back into xml to pretty print it print parse(urllib2.urlopen("http://search.twitter.com/search.atom?&q=python")).toprettyxml(encoding="utf-8")
- Find minimum (or maximum) in a List print min([14, 35, -7, 46, 98]) print max([14, 35, -7, 46, 98])
- Parallel Processing import multiprocessing import math print list(multiprocessing.Pool(processes=4).map(math.exp,range(1,11)))
- Sieve of Eratosthenes There is no Sieve of Eratosthenes operator, but that is hardly a constraint. n = 50 # We want to find prime numbers between 2 and 50 print sorted(set(range(2,n+1)).difference(set((p * f) for p in range(2,int(n0.5) + 2) for f in range(2,(n/p)+1)))) 11 Want to know many bytes a terabyte is? If you know further abbreviations, you can extend the list import pprint;pprint.pprint(zip(('Byte', 'KByte', 'MByte', 'GByte', 'TByte'), (1 << 10i for i in xrange(5)))) 12 what's the largest number that can be represented by 8 Byte? print '\n'.join("%i Byte = %i Bit = largest number: %i" % (j, j8, 256j-1) for j in (1 << i for i in xrange(8)))
13 Function that returns the set of all subsets of its argument f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]
f([10,9,1,10,9,1,1,1,10,9,7]) [[], [9], [10], [9, 10], [7], [9, 7], [10, 7], [9, 10, 7], [1], [9, 1], [10, 1], [9, 10, 1], [7, 1], [9, 7, 1], [10, 7, 1], [9, 10, 7, 1]] -RJW 14 Alternately (shorter, more functional version): f = lambda l: reduce(lambda z, x: z + [y + [x] for y in z], l, [[]]) 15 Decode a base64 encoded file import base64, sys; base64.decode(open(sys.argv[1], "rb"), open(sys.argv[2], "wb"))
16 Editing a list of files in place I came up with this one-liner in response to an article that said it couldn't be done as an one-liner in Python. What this does is replace the substring "at" by "op" on all lines of all files (in place) under the path specified (here, the current path). Caution: Don't run this on your home directory or you're going to get all your text files edited. Toggle line numbers import sys,os,re,fileinput;a=[i[2] for i in os.walk('.') if i[2]] [0];[sys.stdout.write(re.sub('at','op',j)) for j in fileinput.input(a,inplace=1)] Clearer is: import os.path; a=[f for f in os.listdir('.') if not os.path.isdir(f)] 17 Reimplementing cut Print every line from an input file but remove the first two fields. python -c "import sys;[sys.stdout.write(' '.join(line.split(' ')[2:])) for line in sys.stdin]" < input.txt
18 echo unicode character: python -c "print unichr(234)" This script echos "ê"
19 Apply regular expression to lines from stdin [another command] | python -c "import sys,re;[sys.stdout.write(re.sub('PATTERN', 'SUBSTITUTION', line)) for line in sys.stdin]"
20 Modify lines from stdin using map python -c "import sys; tmp = lambda x: sys.stdout.write(x.split()[0]+'\t'+str(int(x.split()[1])+1)+'\n'); map(tmp, sys.stdin);"
21 Display List of all users on Unix-like systems print '\n'.join(line.split(":",1)[0] for line in open("/etc/passwd"))
22 CSV file to json python -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"
23 Compress CSS file python -c 'import re,sys;print re.sub("\s([{};,:])\s", "\1", re.sub("/*.?\/", "", re.sub("\s+", " ", sys.stdin.read())))'
24 Decode string written in Hex python -c "print ''.join(chr(int(''.join(i), 16)) for i in zip([iter('474e552773204e6f7420556e6978')]2))"
25 Retrieve content text from HTTP data python -c "import sys; print sys.stdin.read().replace('\r','').split('\n\n',2)[1]";
26 Prints file extension print '~/python/one-liners.py'.split('.')[-1]
27 Escapes content from stdin This can be used to convert a string into a "url safe" string python -c "import urllib, sys ; print urllib.quote_plus(sys.stdin.read())";
28 Reverse lines in stdin python -c "import sys; print '\n'.join(reversed(sys.stdin.read().split('\n')))"
29 Print top 10 lines of stdin python -c "import sys; sys.stdout.write(''.join(sys.stdin.readlines()[:10]))" < /path/to/your/file
30 Sony's Open Source command line tool for performing python one liners using unix-like pipes They call it "The Pyed Piper" or pyp. It's pretty similar to the -c way of executing python, but it imports common modules and has it's own preset variable that help with splitting/joining, line counter, etc. You use pipes to pass information forward instead of nested parentheses, and then use your normal python string and list methods. Here is an example from the homepage: Here, we take a linux long listing, capture every other of the 5th through the 10th lines, keep username and file name fields, replace "hello" with "goodbye", capitalize the first letter of every word, and then add the text "is splendid" to the end: ls -l | pyp "pp[5:11:2] | whitespace[2], w[-1] | p.replace('hello','goodbye') | p.title(),'is splendid'" and the explanation: This uses pyp's built-in string and list variables (p and pp), as well as the variable whitespace and it's shortcut w, which both represent a list based on splitting each line on whitespace (whitespace = w = p.split()). The other functions and selection techniques are all standard python. Notice the pipes ("|") are inside the pyp command.