Python OOP的全新内容。我正在尝试编写一个代码来分隔列表中的字谜(https://en.wikipedia.org/wiki/Anagram)。来自Leetcode的原始问题在这里(https://leetcode.com/problems/anagrams/)例如:
strs=["eat", "tea", "tan", "ate", "nat", "bat"]
它应该返回:
[['eat', 'tea','tan','ate','nat'], ['bat']]
我看到一些讨论代码,如(https://leetcode.com/discuss/51190/1-line-ruby-python-for-updated-problem):
def groupAnagrams(self, strs):
groups = collections.defaultdict(list)
for s in strs:
groups[tuple(sorted(s))].append(s)
return map(sorted, groups.values())
或(https://leetcode.com/discuss/83032/without-sorting-each-string-use-hash-instead-concise-python)
def groupAnagrams(self, strs):
dic = collections.defaultdict(list)
for str in strs:
dic[reduce(operator.mul, map(hash, str), 1)].append(str)
return map(sorted, dic.values())
问题是:如何让这个类/函数运行以获取列表" strs" 作为输入和输出所需的列表?
groupAnagrams(self,list1)
NameError: name 'self' is not defined
答案 0 :(得分:0)
调用类然后我们将使用方法:
class A(object):
some_method = groupAnagrams
a = A()
print a.some_method(list1)
这会给我们:
[['bat'], ['ate', 'eat', 'tea'], ['nat', 'tan']]