python 计算列表n种组合 -> 得到m种排列方式

博客提及根据列表的值长度判断数量,且无去重功能,还给出原文链接https://diveintopython3.net/advanced-iterators.html 。

原文:https://diveintopython3.net/advanced-iterators.html

>>> import itertools 
>>> perms = itertools.permutations([1, 2, 3], 2) 
>>> next(perms) 
(1, 2)
>>> next(perms)
(1, 3)
>>> next(perms)
(2, 1) 
>>> next(perms)
(2, 3)
>>> next(perms)
(3, 1)
>>> next(perms)
(3, 2)
>>> next(perms) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> import itertools
>>> list(itertools.product('ABC', '123')) 
[''A' ,'1' ),('A' ,'2' ),('A' ,'3' ),('B' ,'1' ),('B' ,'2' ) ,('B' ,'3' ),('C' ,'1' ),('C' ,'2' ),('C' ,'3' )]      
       
      
>>> list(itertools.combinations('ABC', 2)) 
[(('A''B' ),('A''C' ),('B''C']     

根据列表的值长度,判断数量【没有去重功能】

import itertools
names=['Alex', 'Anne', 'Dora', 'John', 'Mike','Chris', 'Ethan', 'Sarah', 'Lizzie', 'Wesley']
groups = itertools.groupby(names, len) 
print(groups)
# <itertools.groupby object at 0x00000207D3702040>
print(list(groups))
# [(4, <itertools._grouper object at 0x00000207D3778070>), (5, <itertools._grouper object at 0x00000207D3778550>), (6, <itertools._grouper object at 0x00000207D541FFD0>)]
groups = itertools.groupby(names, len) 
for name_length, name_iter in groups: 
    print('Names with {0:d} letters:'.format(name_length))
    for name in name_iter:
        print(name)
'''
Names with 4 letters:
Alex
Anne
Dora
John
Mike
Names with 5 letters:
Chris
Ethan
Sarah
Names with 6 letters:
Lizzie
Wesley
'''
>>> list(range(0, 3))
[0, 1, 2]
>>> list(range(10, 13))
[10, 11, 12]
>>> list(itertools.chain(range(0, 3), range(10, 13))) 
[0, 1, 2, 10, 11, 12]
>>> list(zip(range(0, 3), range(10, 13))) 
[(0, 10), (1, 11), (2, 12)]
>>> list(zip(range(0, 3), range(10, 14))) 
[(0, 10), (1, 11), (2, 12)]
>>> list(itertools.zip_longest(range(0, 3), range(10, 14))) 
[(0, 10), (1, 11), (2, 12), (None, 13)]
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值