原文链接:http://www.wklken.me/posts/2013/07/20/python-stackoverflow-vote-top.html#
1:所有可迭代对象都可以被连接,但是连接者总是字符串
代码:
In [38]: tuple = ('nihao', 'world')
In [39]: '-'.join(tuple)
Out[39]: 'nihao-world'
In [40]: list = ['nihao', 'world']
In [41]: '-'.join(list)
Out[41]: 'nihao-world'
2:如何扁平一个二维数组
使用耳机列表表达式
代码:
In [43]: [item for sublist in l for item in sublist]
Out[43]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
3:列表的append和extend的区别
代码:
In [44]: x = [1,2]
In [45]: x.append(3)
In [46]: x.append([4,5])
In [47]: x
Out[47]: [1, 2, 3, [4, 5]]
In [48]: x = [1,2]
In [49]: x.extend(3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-49-1468def59dc4> in <module>()
----> 1 x.extend(3)
TypeError: 'int' object is not iterable
In [50]: x.extend([4,5])
In [51]: x
Out[51]: [1, 2, 4, 5]
append是列表的追加,追加对象没有限制
extend是列表的合并,合并对象为可迭代
4:如何随机从列表中抽取变量
代码:
In [52]: foo = ['a','b','c','d']
In [53]: from random import choice
In [54]: print(choice(foo))
d
In [55]: foo
Out[55]: ['a', 'b', 'c', 'd']
5:如何将一个列表切分成若干个长度相同的子序列
代码:
In [73]: l = range(1,1000)
In [74]: def chunks(l,n):
...: return [l[i:i+n] for i in range(0,len(l), n)]
...:
In [75]: print(chunks(l,10))
6:如何随机生成大写字母和数字组成的字符串
代码:
In [77]: import string, random
In [78]: ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
Out[78]: '5GPRUP'
7:如何判断一个字符串是数字
使用isdigit(但是只能针对于整数组成的字符串有效)
In [83]: a = '1234'
In [84]: a.isdigit()
Out[84]: True
In [89]: a = '123.0'
In [90]: a.isdigit()
Out[90]: False
通用的方法
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
8:获取安装的python模块列表
代码:
In [97]: help('modules')
9:== 和is 在进行比较时候的差别
代码:
In [99]: a = 'pub'
In [100]: b = ''.join(['p','u','b'])
In [101]: b
Out[101]: 'pub'
In [102]: a == b
Out[102]: True
In [103]: a is b
Out[103]: False
In [104]: id(a)
Out[104]: 4460394512
In [105]: id(b)
Out[105]: 4460392376
我们看到is检测的是内存地址是否相同,==是相等检测
10:为何1 in [1,0] == True执行结果是False
代码:
In [108]: 1 in [1,0]
Out[108]: True
In [109]: 1 in [1,0] == True
Out[109]: False
In [110]: (1 in [1,0]) == True
Out[110]: True
In [111]: 1 in ([1,0] = True)
File "<ipython-input-111-ec32f1176011>", line 1
1 in ([1,0] = True)
^
SyntaxError: invalid syntax
这里python使用了比较运算符链
1 in [1,0] == True
被转换为
(1 in [1, 0]) and ([1, 0] == True)
同样的
In [112]: a = 1
In [113]: b = 2
In [114]: c = 3
In [115]: a < b < c
Out[115]: True
会被转为
(a < b) and (b < c) # b不会被解析两次
11:将一个字符串转为一个字典
使用内建模块 ast.literal_eval
代码:
In [116]: s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
In [117]: import ast
In [118]: ast.literal_eval(s)
Out[118]: {'foo': 'kitty', 'muffin': 'lolz'}
In [119]: s = ast.literal_eval(s)
In [120]: s
Out[120]: {'foo': 'kitty', 'muffin': 'lolz'}
12:如何获取Python的site-packages目录位置
代码:
In [125]: from distutils.sysconfig import get_python_lib
In [126]: print(get_python_lib())
/usr/local/Cellar/ipython/6.1.0/libexec/lib/python3.6/site-packages
网友评论