[英]Determine whether for loop is iterating over a list or a generator
Is there a way to tell whether, in python, you are iterating through a list or a generator?有没有办法判断在 python 中,您是在迭代列表还是生成器?
for i in range(10):
print some_param # will identify as a list
for i in xrange(10):
print some_param # will identify as a generator
In general, no.一般来说,没有。 You can do unpleasant things like isinstance(my_iterable, type(iter(xrange(1))))
vs isinstance(my_iterable, type(iter([])))
, but with the bare iterator interface, generators and lists are indistinguishable to their clients.您可以做一些不愉快的事情,例如isinstance(my_iterable, type(iter(xrange(1))))
与isinstance(my_iterable, type(iter([])))
,但是使用裸迭代器接口,生成器和列表无法区分客户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.