Python数据结构之集合Set
2017-07-02 11:01
639 查看
python中的Set()数据结构具有的一个特殊属性就是Set()中不存在重复元素
1、集合定义
2、向Set中添加元素
3、Set中的元素排序
For any set
anything else iterable),
a list of the elements of
sorted order:
For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Retur:
[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
两个词如果是anagrams就把它们转为同一个值.
一般有两种转法,比如’tea’和’eat’排序后都可转为’aet’,或者统计字母出现的次数,两个都是((‘a’, 1), (‘e’, 1), (‘t’, 1)),然后再把这个转后的东西作为哈系表的键值key,对应的anagrams list作为value存进去。
参考:http://sahandsaba.com/interview-question-facebook-anagrams.html
1、集合定义
a=set()
2、向Set中添加元素
a = set([1,2,3,4]) ##用add a.add(5) ##用或运算符号 a |= {6}
##Set还有个update函数,可以接受多组参数一次添加到set里
a.update([5,6,3], [-11,11])
3、Set中的元素排序
For any set
s(or
anything else iterable),
sorted(s)returns
a list of the elements of
sin
sorted order:
b = sorted(a) # sorted方法将返回一个list,而不是set
一道Leetcode
Group Anagrams
Given an array of strings, group anagrams together.For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Retur:
[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
两个词如果是anagrams就把它们转为同一个值.
一般有两种转法,比如’tea’和’eat’排序后都可转为’aet’,或者统计字母出现的次数,两个都是((‘a’, 1), (‘e’, 1), (‘t’, 1)),然后再把这个转后的东西作为哈系表的键值key,对应的anagrams list作为value存进去。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ result = {} for word in strs: hash_key = ''.join(sorted(word)) if hash_key in result: result[hash_key] += [word] else: result[hash_key] = [word] return [tuple(sorted(lst)) for lst in result.values() ] |
相关文章推荐
- python 数据结构-集合set
- python基础数据结构——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- Python:数据结构(list, tuple, Dict & Set)
- python基本数据类型之集合set
- Redis-数据结构(字符串集合set)
- python基础知识——内置数据结构(集合)
- 集合框架体系结构,list、set操作数据,泛型(一)
- Redis-数据结构(有序字符串集合sorted set)
- python数据结构之集合
- Python核心数据类型——集合(Set)
- Python基础,基本类型(整型,浮点数等)数据结构(List,dic(Map),Set,Tuple),控制语句(if,for,while,continue or break):来自学习资料
- Python基础数据类型-列表(list)和元组(tuple)和集合(set)
- Redis 数据结构之有序集合(sort set)
- JavaScript数据结构与算法之集合(Set)
- 【Python】10、python内置数据结构之集合
- set(集合)数据结构
- 7、python数据类型之集合set
- JavaScript数据结构与算法之集合(Set)
- python 数据结构六 之 字典与集合
- Python基础数据结构之大循环(for list,set,dict,tuple)