isinstance(x,list)当迭代包含字符串和列表的列表时 [英] isinstance(x, list) when iterating a list containing strings and lists
问题描述
在迭代嵌套列表自内向外中,我被告知类型检查不是Pythonic。一般来说,这是真的:我们只想看界面(鸭子类型),而不是一个特定的类型。
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.
问题询问窗体的嵌套列表 ['a',['c',['e'],'d'],'b']
,我们特别考虑字符串原子(不可迭代)。所以,我们不能使用毯子 collections.Iterable
,但另一方面 isinstance(x,list)
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.
我的回答是
def traverse(l):
for x in l:
if isinstance(x, list):
traverse(x)
callback(l)
什么是更好的方法?或者 isinstance
确定这里?
What's a better approach? Or is isinstance
OK here?
推荐答案
确定这里 - 虽然我可以更改为
I think that your answer is OK here -- Although I might change it to
if not isinstance(x,basestring):
...
以根据预期的输入更多地接受。最终,你需要的一些问题 isinstance
这就是为什么它仍然存在于语言。
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.
话虽如此,关于这个问题,非pythonic的事情是数据结构。在python中,如果一个问题看起来很难,这可能意味着你以错误的方式存储数据...(当然,我意识到你不能控制其他问题的数据结构的原始海报是什么; - )。
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 ;-).
基本上,我想我的观点是 isinstance
是 hack 你需要做柠檬水,当你的同事/一些图书馆作家在某处给你柠檬 - 否则你尽可能避免它。
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.
这篇关于isinstance(x,list)当迭代包含字符串和列表的列表时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!