题目描述
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单shilie
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = {}
for element in strs:
t = ''.join(sorted(element))
if t in dic:
dic[t].append(element)
else:
dic[t] = [element]
return list(dic.values())
查漏补缺:
join函数
#功能:用于将序列中的元素以指定的字符连接生成一个新的字符串
#语法:str.join(sequence)
#str:分隔符,可以为空
#sequence:要连接的元素序列
#返回值为生成的新字符串
#对序列进行操作,以空格“ ”,“-”作为分隔符
list1=["hi","hello","how are you"]
print(list1)
q=" ".join(list1)
x="-".join(list1)
print(q)
print(x)
运行结果:
[‘hi’, ‘hello’, ‘how are you’]
hi hello how are you
hi-hello-how are you
#对字符串进行操作
str="What a sunny day!"
print(":".join(str))
运行结果:(本身结果是无空格的,但是会乱码就手动加了)
W:h: a :t: : a: : s:u:n:n:y: :d: a:y:!
其他
Python 列表list详解(超详细)_python list-优快云博客
Python字典(Dictionary)操作全解【创建、读取、修改、添加、删除、有序字典、浅复制、排序】_python dictionary 依次读取-优快云博客