我需要构建一个生成器,我正在寻找一种方法来缩短这个循环到一行.我尝试枚举但是没有用.
counter=0
for element in string:
if function(element):
counter+=1
yield counter
else:
yield counter
Run Code Online (Sandbox Code Playgroud) 给定一个字符串,我们如何检查它的任何字谜是否可以作为回文?
例如,让我们考虑字符串"AAC".它的字谜是"ACA",它是一个回文.如果我们可以从给定字符串的任何anagram形成回文,我们必须编写一个接受字符串并输出true的方法.否则输出错误.
这是我目前的解决方案:
from collections import defaultdict
def check(s):
newdict = defaultdict(int)
for e in s:
newdict[e] += 1
times = 0
for e in newdict.values():
if times == 2:
return False
if e == 1:
times += 1
return True
Run Code Online (Sandbox Code Playgroud)
使用python库的任何更短的解决方案?
我怎样才能写出function哪些应该返回嵌套在iterable中的每个值?
这是我想要完成的一个例子:
for i in function([1, 2, [3, 4, (5, 6, 7), 8, 9], 10]):
print(i, end=' ')
Run Code Online (Sandbox Code Playgroud)
预期产量:
1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)