翻译自Quora, 读来比较有趣, 文中列举的十个特性基本都算语法糖一类的东西, 从中可以窥见 python 的设计理念. 而且, 很有趣的是, 我发现这些特性, Scala 里也基本都有的~~其他几个答案也不错, 原文见这里: What are the 10 best features of Python?
特性1: 反转字符串
>>> a = "codementor"
>>> print "Reverse is",a[::-1]
Reverse is rotnemedoc
特性2: 矩阵转置
>>> mat = [[1, 2, 3], [4, 5, 6]]
>>> zip(*mat)
[(1, 4), (2, 5), (3, 6)]
特性3: 将列表中的所有三个值存储在3个新变量中
>>> a = [1, 2, 3]
>>> x, y, z = a
>>> x
1
>>> y
2
>>> z
3
特性4: 列表转字符串
a = ["Code", "mentor", "Python", "Developer"]
>>> print " ".join(a)
Code mentor Python Developer
特性5: 列表拉链
原文:
List 1 = [‘a’, ‘b’, ‘c’, ‘d’]
List 2 = [‘p’, ‘q’, ‘r’, ‘s’]
Write a Python code to print
ap
bq
cr
ds
>>> for x, y in zip(list1,list2):
... print x, y
...
a p
b q
c r
d s
特性6: 一行代码交换两个值
>>> a=7
>>> b=5
>>> b, a =a, b
>>> a
5
>>> b
7
特性7: 不使用循环, 打印 ‘codecodecodecode mentormentormentormentormentor’
>>> print "code"*4+' '+"mentor"*5
codecodecodecode mentormentormentormentormentor
特性8: 多重嵌套列表转单一列表
如:
a = [[1, 2], [3, 4], [5, 6]]
转为 Output:- [1, 2, 3, 4, 5, 6]
>>> import itertools
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
特性9: 检查两个单词是否是相互颠倒的
def is_anagram(word1, word2):
"""Checks whether the words are anagrams.
word1: string
word2: string
returns: boolean
"""
实现:
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
>>> is_anagram('abcd','dbca')
True
>>> is_anagram('abcd','dbaa')
False
特性10: 一行代码获取用户输入并放到列表中
input: “1 2 3 4 ”
return [1,2,3,4]
>>> result = map(lambda x:int(x) ,raw_input().split())
1 2 3 4
>>> result
[1, 2, 3, 4]