开发者

Convert Any Iterable to Array in Python

This just has to be a dupe, but I just didn't find any ex开发者_JAVA技巧isting instance of this question...

What is the easiest way to convert any iterable to an array in Python (ideally, without importing anything)?

Note: Ideally, if the input is an array then it shouldn't duplicate it (but this isn't required).


It depends on what you mean by array. If you really mean array and not list or the like, then you should be aware that arrays are containers of elements of the same (basic) type (see http://docs.python.org/library/array.html), i.e. not all iterables can be converted into an array. If you mean list, try the following:

l = list(iterable)


If by "array" you mean a list, how about:

list(foo)


What about [e for e in iterable]?

And, to satisfy the extra requirement:

iterable if isinstance(iterable,list) else [e for e in iterable]


The list function takes an iterable as an argument and returns a list. Here's an example:

>>> rng = xrange(10)
>>> rng
xrange(10)
>>> list(rng)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This won't create a list of lists, either:

>>> list(list(rng))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Basically, arrays and lists are more or less the same thing in python. So a list comprehension will do the job:

  ary = [ i for i in yourthing ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜