搜索
查看: 524|回复: 0

迭代工具:实现python排列组合

[复制链接]

1839

主题

2255

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
11913
发表于 2015-7-28 09:05:03 | 显示全部楼层 |阅读模式
和collections库一样,还有一个库叫itertools,对某些问题真能高效地解决。其中一个用例是查找所有组合,他能告诉你在一个组中元素的所有可能的组合方式
  1. from itertools import combinations
  2. teams = ["a", "b", "c", "d"]
  3. for game in combinations(teams, 2):
  4.     print game
  5. >>> ('a', 'b')
  6. >>> ('a', 'c')
  7. >>> ('a', 'd')
  8. >>> ('b', 'c')
  9. >>> ('b', 'd')
  10. >>> ('c', 'd')
复制代码

  1. >>> import itertools
  2. >>> list(itertools.combinations('abc', 2))
  3. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  4. >>> list(itertools.permutations('abc',2))
  5. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  6. >>>
复制代码




[url=http://static.wooyun.org/upload/image/201507/2015072719173454967.jpg][/url]

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?Join BUC

x
过段时间可能会取消签到功能了
您需要登录后才可以回帖 登录 | Join BUC

本版积分规则

Powered by Discuz!

© 2012-2015 Baiker Union of China.

快速回复 返回顶部 返回列表