Python 在字符串列表中查找最唯一的字符
最近加入了python代码俱乐部,所以不是学校作业 任务: 编写一个函数Python 在字符串列表中查找最唯一的字符,python,python-3.x,string,list,Python,Python 3.x,String,List,最近加入了python代码俱乐部,所以不是学校作业 任务: 编写一个函数coolest_word(words),返回最酷的单词(如果存在) 酷的定义是一个词有多少个独特的字符 例如,单词“decomposition”具有10个唯一字母。 你的工作是从给定的单词列表中找出最酷的单词并返回 如果列表为空,则返回None。如果出现平局,请返回其中一个单词 到目前为止,我的解决方案是: words = ['expectation', 'discomfort', 'half', 'decompositio
coolest_word(words)
,返回最酷的单词(如果存在)
酷的定义是一个词有多少个独特的字符
例如,单词“decomposition”
具有10个唯一字母。
你的工作是从给定的单词列表中找出最酷的单词并返回
如果列表为空,则返回None
。如果出现平局,请返回其中一个单词
到目前为止,我的解决方案是:
words = ['expectation', 'discomfort', 'half', 'decomposition']
def coolest_word(words):
length = 0
unique = ['']
for i in words:
if (len(words) != 0 and len(set(i)) > length):
length = len(set(i))
unique[0] = i
else:
unique[0] = ('None')
return(unique)
print(coolest_word(words))
我已选择将列表
更改为集
,然后比较集
的唯一字符。由于set
不考虑重复变量,这似乎是个好主意
只要for循环找到一个较长的集合(包含更多变量),它就会被覆盖到唯一的集合中,以便记忆并在以后调用
现在的问题是,如果给定的列表为空,unique将返回['']
,我不理解为什么
正如在第二部分中一样,如果列表为空,我希望unique被覆盖,但它不会这样做
有什么想法吗?如果您的输入列表单词
为空,即单词=[]
,您将无法进入for循环。并且您没有定义在输入列表为空的情况下,unique
应该发生什么
试试这个:
words = ['expectation', 'discomfort', 'half', 'decomposition']
def coolest_word(words):
length = 0
unique = ['']
if not words: # If input list is empty set unique as None.
unique[0] = 'None'
for i in words:
if (len(words) != 0 and len(set(i)) > length):
length = len(set(i))
unique[0] = i
else:
unique[0] = ('None')
return(unique)
print(coolest_word(words))
但我建议的一个更好的方法是使用None
初始化unique
列表,即unique=['None']
而不是unique=['']
。通过这种方式,您可以保持所有代码的原样。您可以使用set
获取单词中的唯一元素,并使用len
查找单词中有多少唯一元素
words = ['expectation', 'discomfort', 'half', 'decomposition']
def coolest_word(wlist):
k = {i:len(set(i)) for i in wlist}
return max(k, key=k.get)
print(coolest_word(words))
输出:
'decomposition'
解释
如果你打印(k)
它会给你
{'expectation': 9, 'discomfort': 9, 'half': 4, 'decomposition': 10}
max(k,key=k.get)
将返回具有最高值(max value)的键
k.get
将获取键的值
例如
输出:
4
如果给定列表为空,则跳过整个for循环。因此,您只需通过以下方式初始化
unique
:
unique = ['None']
words = ['expectation', 'discomfort', 'decomposition', 'half']
此外,您还必须删除for循环中的else
分支,因为一旦您发现一个单词没有重复的字母,它就会覆盖结果(要测试我说的内容,请尝试以这种方式洗牌输入列表:
unique = ['None']
words = ['expectation', 'discomfort', 'decomposition', 'half']
你会得到“无”而不是“分解”
附录:您甚至可以简化您的if条件,替换
if (len(words) != 0 and len(set(i)) > length)
与
因为如果len(words)
实际上是0
,您甚至不会进入for循环。使用键和默认值都可以简单地应用
def coolest_word(words):
return max(words, key=lambda w: len(set(w)), default=None)
演示:
如果列表是空的,那么你永远不会进入你的循环,所以你的唯一性是unique=[''']
这不是空的,这是一个包含一个空字符串的列表。顺便说一下,我们被建议使用max,key=function,但我没能理解它。如果你能再解释一下,我将不胜感激!你能解释一下什么“如果不是单词的话”:在这种情况下会吗?这会检查列表word
是否为空或包含任何元素。这与我们检查列表长度>0
相同。哇,你的建议..这是我自己应该想到的。谢谢!
>>> coolest_word(['expectation', 'discomfort', 'half', 'decomposition'])
'decomposition'
>>> [coolest_word([])] # Wrap in a list because None by itself doesn't get printed
[None]