原始问题:有人可以告诉我如何使用“切片列表”和“省略号”吗?它们什么时候有用?谢谢。
以下是关于“slice_list”和“ellipsis”的语言定义;Alex Martelli 的回答指出了它们的起源,这不是我所设想的。
[ http://docs.python.org/reference/expressions.html#tok-slicing][1]
5.3.3. 切片
扩展切片 ::= 主“[”切片列表“]”
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= 表达式 | 适当的切片 | 省略
省略号 ::= "..."
[1]: http ://docs.python.org/reference/expressions.html#tok-slicing
如果有人(就像我一样)正在寻找使用切片列表攻击列表(或列表列表)的方法,这里有 5 种方法可以从列表中获取由切片列表选择的元素列表和 2 种对列表执行相同操作的方法,在这种情况下,每个列表应用一个切片。输出在最后的评论中。我发现 h5,使用嵌套 for 循环的示例,如果不使用(更新)有意义的变量名,最难理解。
#!/usr/bin/env python
import itertools
puz = [(i + 100) for i in range(40)]
puz1 = list( puz)
puz2 = [(i + 200) for i in range(40)]
puz3 = [(i + 300) for i in range(40)]
puzs = [puz1,puz2,puz3]
sa = slice( 0,1,1)
sb = slice( 30,39,4)
sc = slice( -1, -15,-5)
ss = [sa,sb,sc]
def mapfunc( a,b):
return a[b]
f = map( mapfunc,[puz] * len(ss),ss)
print "f = ", f #same as g below
g = [ puz[i]
for i in ss ]
print "g = ",g #same as f, above
h1 = [ i
for i in itertools.chain( puz[sa],puz[sb],puz[sc]) ]
print "h1 = ", h1 #right
h2 = [ i
for i in itertools.chain( *(map( mapfunc,[puz] * len(ss),ss))) ]
print "h2 = ",h2 #right
h3 = [ i
for i in itertools.chain( *f) ]
print "h3 = ",h3 #right
h4 = [ i
for i in itertools.chain( *g) ]
print "h4 = ", h4 #also right
h5 = []
for slice_object in ss:
for list_element in puz[slice_object]:
h5.append( list_element)
print "h5 = ", h5 #right, too
print "=============================="
hh1 = [ i
for i in itertools.chain( *(map( mapfunc,puzs,ss))) ]
print "hh1 = ",hh1 #right
puz_s_pairs = zip( puzs,ss)
#print "puz_s_pairs = ",puz_s_pairs
hh2 = [ i
for i in itertools.chain( *(map( mapfunc,*zip( *puz_s_pairs)))) ]
print "hh2 = ",hh2 #right
'''
>>> execfile(r'D:/cygwin/home/usr01/wrk/py/pyexpts/list_of_slices_of_list.02.py')
f = [[100], [130, 134, 138], [139, 134, 129]]
g = [[100], [130, 134, 138], [139, 134, 129]]
h1 = [100, 130, 134, 138, 139, 134, 129]
h2 = [100, 130, 134, 138, 139, 134, 129]
h3 = [100, 130, 134, 138, 139, 134, 129]
h4 = [100, 130, 134, 138, 139, 134, 129]
h5 = [100, 130, 134, 138, 139, 134, 129]
==============================
hh1 = [100, 230, 234, 238, 339, 334, 329]
hh2 = [100, 230, 234, 238, 339, 334, 329]
'''