Man*_*tis 5 python iteration list-comprehension data-structures
如果我在python中有一个列表,例如:
stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
长度为n(在本例中为9),我有兴趣创建长度为n/2的列表(在本例中为4).我想要原始列表中所有可能的n/2值集合,例如:
[1, 2, 3, 4], [2, 3, 4, 5], ..., [9, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
是否有一些列表理解代码我可以用来迭代列表并检索所有这些子列表?我不关心列表中值的顺序,我只是想找到一个生成列表的聪明方法.
你需要的是来自itertools的组合函数 (编辑:如果顺序很重要,请使用排列)
请注意,此功能在Python 2.5中不可用.在这种情况下,您可以复制以上链接中的代码:
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
Run Code Online (Sandbox Code Playgroud)
然后
stuff = range(9)
what_i_want = [i for i in combinations(stuff, len(stuff)/2)]
Run Code Online (Sandbox Code Playgroud)
>>> stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> n=len(stuff)
>>>
>>> [(stuff+stuff[:n/2-1])[i:i+n/2] for i in range(n)]
[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 1], [8, 9, 1, 2], [9, 1, 2, 3]]
>>>
Run Code Online (Sandbox Code Playgroud)
注意:上面的代码基于您的示例中的假设
[1, 2, 3, 4], [2, 3, 4, 5], ..., [9, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
如果您确实需要所有可能的值,则需要使用其他人建议的itertools.permutations或组合函数.
| 归档时间: |
|
| 查看次数: |
354 次 |
| 最近记录: |