十行以內,你寫過哪些比較酷的 Python 代碼?

每行不要超過80字元

十行以內,你寫過哪些比較酷的Matlab代碼? - 編程

十行以內,你寫過哪些比較酷的Mathematica代碼? - Wolfram Mathematica


我覺得比較酷的one-line tree in python:

In [1]: from collections import defaultdict

In [2]: def tree(): return defaultdict(tree)

In [3]: users = tree()
...: users[harold][username] = hrldcpr
...: users[handler][username] = matthandlersux

In [4]: import json

In [5]: print(json.dumps(users))
{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}


還是純函數式(不使用python的list)的鏈表實現吧,雖然挺簡單的,但是接觸函數式編程之前還真沒想過能這麼干

# cons.py
def cons(x,y):
return lambda m:m(x,y)
def car(z):
return z(lambda p,q: p)
def cdr(z):
return z(lambda p,q: q)

使用:

python -i cons.py
&>&>&> a = cons(1, cons(2, cons(3,4)))
&>&>&> car(a)
1
&>&>&> cdr(a)
& at 0x10c805aa0&>
&>&>&> car(cdr(cdr(a)))
3

改編自:Structure and Interpretation
of Computer Program s 2.1.3


一些很經典的演算法用Python寫起來好像都挺短的,leetcode上好多都很短~~

比如這個最長不重複子串LNRS的,用了DP+Hash, 才9行……

def lengthOfLongestSubstring(self, s):
hashtable = [-1] * 128
left = maxlength = 0
for right in range(0, len(s)):
if hashtable[ord(s[right])] &>= left:
left = hashtable[ord(s[right])] + 1
hashtable[ord(s[right])] = right
maxlength = right - left + 1 if right - left + 1 &> maxlength else maxlength
return maxlength


今天在項目里找到一個之前隨手寫下的簡單模板渲染函數,去掉注釋稍微精簡了一下達到了十行之內的要求:

import re
def template_render(template, model):
parts = []
for part in re.split(r"{{([.w]+?)}}", template):
parts.append(str(part if len(parts) % 2 == 0 else
reduce(lambda m, k: m[k], part.split("."), model)))
return "".join(parts)

使用方法:

model = {
"name": "lyc",
"foo": {
"bar": "hello"
}
}
template = "{{foo.bar}} {{name}}"

print template_render(template, model)

輸出:

hello lyc


一行生成字元畫。


print self,不過看過 Sina Visitor System 的那個版本,我覺得我還需要提高姿勢水平。

print (lambda s:s.replace(chr(042),chr(047))%s)(print (lambda s:s.replace(chr(042), chr(047))%%s)("%s"))


曾經在ChinaUnix論壇上回答一個Python練習題,寫了約十行代碼。用到了Python的全排列產生器,自己覺得還是Python的有些功能寫起程序來還是滿酷的。

問題:

a-b=c

d/e=f

g+h=i

c*f=i

這幾個字母是1-9 9個數字 9個數字各不相等 用python算出來 要怎麼寫?

代碼:

如何用python解這道題-Python-ChinaUnix.net

歡迎Pythoner們來這個論壇交流。


謝要,但是抱歉啊。。。。你被我的名字忽悠了。。。。。我的專業是臨床醫學。。。。如果有想了解骨科相關知識可以找我。。。


帥不過一行……→_→

[[re.sub("[

]|((?&<=s) )|( (?=s))","",k.text) for k in j] for j in [[i[0],]+i[2:6] for i in [K for K in table.iter() if K.tag == "tr"][1:]]]

這是用來解析教務系統成績單的……


True, False = False, True


其實這也算是工具了

cat response.json |python -m json.tool

這樣就格式化json了

---------------------

經常有這種情況:公司的伺服器要通過堡壘機才能聯上,按OPS的流程從伺服器上拷東西時,要先從伺服器拷到堡壘機,再從堡壘機拷到自己機器上,煩的要死啊。於是用python搞一個HTTP伺服器了。

python -m SimpleHTTPServer 9999

ok了,直接wget就好了


快速排序?

def quickSort(src):
if len(src) &<= 1: return src pivotValue = src[0] leftSrc = quickSort(filter(lambda x: x& pivotValue, src[1 : ]))
return leftSrc+[pivotValue]+rightSrc


元類

以下代碼作用是將以它為元類的類的屬性全部轉換為列印自己的屬性名的函數.

class WeOnlyPrintOurNames(type):
def __new__(cls, name, bases, attrs):
def wrapper(x):
@staticmethod
def self_print():
print x.replace(_, )
return self_print
attrs = dict(zip(attrs.keys(), [wrapper(x) for x in attrs.keys()]))
return super(WeOnlyPrintOurNames, cls).__new__(cls, name, bases, attrs)

試一試:

class ILovePy():
__metaclass__ = WeOnlyPrintOurNames
Im_Pythoner = None
ILovePy.Im_Pythoner()


brainfuck語言的解釋器,用Python寫可以只有一行(很長)

brainfuck語言嘛,誰用誰知道


sublime text的包管理安裝就是一行很長的python 按字數分割後應該符合要求~


import this


只有一行

print "hello, world"


def function1():

Xxxxxxx

def function2():

Xxxxxxxx

print case*function1()+ (note case)*function2()

條件case成立的情況下列印函數1的值,否則列印函數2的值。


import this

會出來zen of Python:

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases arent special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless youre Dutch.

Now is better than never.

Although never is often better than *right* now.

If the implementation is hard to explain, its a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- lets do more of those!

然後this的源代碼其實是一個類似凱撒加密的字元串。。。

實在想不出什麼高大上的10行Python,拿這個湊數吧


推薦閱讀:

Python 參數傳引用還是傳值?
如何用Python智能批量壓縮圖片?
Python 開發中有哪些高級技巧?
有哪些關於 Python 的技術博客?
使用Python定製詞雲

TAG:Python | 調查類問題 | 編程 | 代碼 |