问题
At Iterating nested list inside-out, I was told that "type-checking isn't Pythonic". Generally, this is true: we want to look only at the interface (duck-typing) rather than a specific type.
The question asks about nested lists of the form ['a', ['c', ['e'], 'd'], 'b']
, and we specifically consider strings atomic (non-iterable). So, we can't use a blanket collections.Iterable
, but on the other hand isinstance(x, list)
does seem a bit hacky.
My answer was
def traverse(l):
for x in l:
if isinstance(x, list):
traverse(x)
callback(l)
What's a better approach? Or is isinstance
OK here?
回答1:
I think that your answer is OK here -- Although I might change it to
if not isinstance(x,basestring):
...
to make it a little more accepting depending on the expected input. Ultimately, some problems you need isinstance
which is why it still exists in the language.
That being said, the thing about this problem that is un-pythonic is the data-structure. In python, if a problem seems really hard, it probably means you're storing the data in the wrong way ... (Of course, I realize that you had no control over what the original poster of the other question's data structure was ;-).
Basically, I guess that my view is that isinstance
is the hack that you need to make lemonade when your colleagues/some library writer somewhere gives you lemons -- Otherwise you avoid it where possible.
来源:https://stackoverflow.com/questions/14961601/isinstancex-list-when-iterating-a-list-containing-strings-and-lists