检查对象是否是字符串列表而不是嵌套循环的优雅方法是什么?可能这里必须有构造结构化迭代的常规方法。
升级版
像这样的:
l = [['a', 'b', 'c'], ['d', 1], 3, ['e', 2, 'f']]
def recurse(iterable, levels):
results = []
try:
fn = levels[0]
except IndexError:
return
for e in iterable:
results.append(fn(e))
try:
results.extend(recurse(e, levels[1:]))
except TypeError:
pass
return results
instance_of = lambda t: lambda e: isinstance(e, t)
print(recurse(l, [instance_of(list), instance_of(basestring)]))
升级版#2
我做了一些自制的函数式编程,现在它检查字符串列表:
from collections import Iterable
from itertools import imap, chain
def compose(f, g):
return lambda *a, **kw: f(g(*a, **kw))
def concat(iterable):
return chain.from_iterable(iterable)
def mk_iter(o):
if isinstance(o, Iterable):
return o
else:
return [o]
def put_in(f, g):
"""To support spirit of the Olympics :)"""
return lambda e: concat(
[mk_iter(f(e)),
concat(imap(compose(mk_iter, g), mk_iter(e)))]
)
ckr = lambda t: lambda e: isinstance(e, t)
l = [[['a', 'b'], ['c']], [['d'], ['1']], [1]]
fns = [ckr(list), ckr(list),ckr(list), ckr(str)]
fns.reverse()
print(list(reduce(lambda x, y: put_in(y, x), fns)(l)))
最佳答案
lol = [["a", "b"], ["c"], ["d", "e"], [1]]
from itertools import chain
print isinstance(lol, list) and all(isinstance(items, list) \
and all(isinstance(item, str) for item in items) for items in lol)
关于python - 检查对象是否为字符串列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21723910/