【Python】itertools内置函数

  • permutations

import itertools
# from itertools import permutations
# permutations返回list的全排列
print(list(itertools.permutations([1, 2, 3])))
# 后一位2
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# 后一位3
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
# 不填默认是list的长度
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

# 在实际使用过程中,将元组变为list
resultpermu = [list(i) for i in itertools.permutations([1, 2, 3])]
print(resultpermu)
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

# 需要注意的是函数是根据他们的位置来计算组合的,而不是他们的值,所以有重复的结果。
print(list(itertools.permutations([1,1,2])))
# [(1, 1, 2), (1, 2, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (2, 1, 1)]
rs = []
# 去重
for i in itertools.permutations([1, 1, 2]):
    if list(i) not in rs:
        rs.append(list(i)[:])
print(rs)
# [[1, 1, 2], [1, 2, 1], [2, 1, 1]]

Python:itertools模块 combinations和product的使用

  • combinations(iterabler)

 创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序:

combinations('ABCD', 2) --> AB AC AD BC BD CD
combinations(range(4), 3) --> 012 013 023 123
  • product(*iterables[, repeat])  

创建一个迭代器,生成表示iterables中的项目的笛卡尔积的元组,repeat表示重复生成序列的次数。

product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111

product是每个数字都去组合一遍

【Python】itertools内置函数_第1张图片

combinations是按位置结合一遍

【Python】itertools内置函数_第2张图片

搓搓手

print('-----combinations-------')
nums1 = [1,2,3]
nums2 = [1,1,2]
print(list(itertools.combinations(nums1,3)))
# [(1, 2, 3)] # 三个数字三三组合当然只有一个
print(list(itertools.combinations(nums1,2)))
# [(1, 2), (1, 3), (2, 3)] 三个数字量量组合,有多少的结果
print(list(itertools.combinations(nums2,2)))
# [(1, 1), (1, 2), (1, 2)]

print('----------product---------------')
print(list(itertools.product(nums1,repeat=2)))
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
# 如果repeat=3
# 在=2的基础上,每一项再找一遍
# [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3),
# (1, 3, 1), (1, 3, 2), (1, 。。。
print(list(itertools.product('abc','134')))
# [('a', '1'), ('a', '3'), ('a', '4'), ('b', '1'), ('b', '3'), 
# ('b', '4'), ('c', '1'), ('c', '3'), ('c', '4')]
# repeat默认=2

差别!!
print(list(itertools.combinations(nums1,2)))
# [(1, 2), (1, 3), (2, 3)] 三个数字量量组合,有多少的结果
print(list(itertools.product(nums1,repeat=2)))
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
  • groupby

Python中的分组函数(groupby、itertools)

groupby()把迭代器中相邻的重复元素挑出来放在一起

>>> for key, group in itertools.groupby('AAABBBCCAAA'):
...     print key, list(group) # 为什么这里要用list()函数呢?
不用list的话是,返回的是一个对象
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']

实际上挑选规则是通过函数完成的,只要作用于函数的两个元素返回的值相等,这两个元素就被认为是在一组的,而函数返回值作为组的key。如果我们要忽略大小写分组,就可以让元素'A''a'都返回相同的key:

>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
...     print key, list(group)
...
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']

搓搓手

str1 = "cataaaaa"
str2 = "aaabbbbcccc"
for key,group in itertools.groupby(str1):
    print(key,list(group))
# c ['c']
# a ['a']
# t ['t']
# a ['a', 'a', 'a', 'a', 'a']
for key,group in itertools.groupby(str2):
    print(key,list(group))
# a ['a', 'a', 'a']
# b ['b', 'b', 'b', 'b']
# c ['c', 'c', 'c', 'c']
aftergroupby = itertools.groupby(str2)
print(aftergroupby) # 
# 需要通过for取出来值


import collections
# trydict = collections.defaultdict(str2) # TypeError: first argument must be callable or None
# 这里str2不是空的,所以报错
# for key,value in trydict:
#     print(key,value)

blog的内容,是字典的操作,就学习着吧。。。? 

from operator import itemgetter #itemgetter用来去dict中的key,省去了使用lambda函数
from itertools import groupby #itertool还包含有其他很多函数,比如将多个list联合起来。。
d1={'name':'zhangsan','age':20,'country':'China'}
d2={'name':'wangwu','age':19,'country':'USA'}
d3={'name':'lisi','age':22,'country':'JP'}
d4={'name':'zhaoliu','age':22,'country':'USA'}
d5={'name':'pengqi','age':22,'country':'USA'}
d6={'name':'lijiu','age':22,'country':'China'}
lst=[d1,d2,d3,d4,d5,d6]

#通过country进行分组:

lst.sort(key=itemgetter('country')) #需要先排序,然后才能groupby。lst排序后自身被改变
lstg = groupby(lst,itemgetter('country')) 
#lstg = groupby(lst,key=lambda x:x['country']) 等同于使用itemgetter()


for key,group in lstg:
    for g in group: #group是一个迭代器,包含了所有的分组列表
        print key,g
返回:
China {'country': 'China', 'age': 20, 'name': 'zhangsan'}
China {'country': 'China', 'age': 22, 'name': 'lijiu'}
JP {'country': 'JP', 'age': 22, 'name': 'lisi'}
USA {'country': 'USA', 'age': 19, 'name': 'wangwu'}
USA {'country': 'USA', 'age': 22, 'name': 'zhaoliu'}
USA {'country': 'USA', 'age': 22, 'name': 'pengqi'}


print [key for key,group in lstg] #返回:['China', 'JP', 'USA']


print [(key,list(group)) for key,group in lstg]
#返回的list中包含着三个元组:
[('China', [{'country': 'China', 'age': 20, 'name': 'zhangsan'}, {'country': 'China', 'age': 22, 'name': 'lijiu'}]), ('JP', [{'country': 'JP', 'age': 22, 'name': 'lisi'}]), ('USA', [{'country': 'USA', 'age': 19, 'name': 'wangwu'}, {'country': 'USA', 'age': 22, 'name': 'zhaoliu'}, {'country': 'USA', 'age': 22, 'name': 'pengqi'}])]


print dict([(key,list(group)) for key,group in lstg])
#返回的是一个字典:
{'JP': [{'country': 'JP', 'age': 22, 'name': 'lisi'}], 'China': [{'country': 'China', 'age': 20, 'name': 'zhangsan'}, {'country': 'China', 'age': 22, 'name': 'lijiu'}], 'USA': [{'country': 'USA', 'age': 19, 'name': 'wangwu'}, {'country': 'USA', 'age': 22, 'name': 'zhaoliu'}, {'country': 'USA', 'age': 22, 'name': 'pengqi'}]}


print dict([(key,len(list(group))) for key,group in lstg])
#返回每个分组的个数:
{'JP': 1, 'China': 2, 'USA': 3}

所以在 leetcode49 中可以这样解决(还是有点不明白)

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
def groupAnagrams(self, strs):
    groups = collections.defaultdict(list)
    for s in strs:
        groups[tuple(sorted(s))].append(s)
    return map(sorted, groups.values())

 

你可能感兴趣的:(编程语言)