Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Single vs multi-dimensional array

Is there any way to programmatically determine if the array you are parsing is a regular array or a two dimensional array?
For example, how would you distinguish:
array1 = ["This", "Is", "A", "Sample", "Array", "."]
from
array2 = [["This", "Is"], ["A", "Sample"], ["Array", "."]]
(Mar 1, 2014 03:06 PM)_UserName_ Wrote:  Is there any way to programmatically determine if the array you are parsing is a regular array or a two dimensional array?
For example, how would you distinguish:
array1 = ["This", "Is", "A", "Sample", "Array", "."]
from
array2 = [["This", "Is"], ["A", "Sample"], ["Array", "."]]

A really really ghetto way of doing it could be:

Code
if str(array2).count("[") > 1 and str(array2).count("],") > 1:
    print "Multi dimensional"
else:
      print "One dimensional"
You can use type() to check the type of something. If you check the first item in the list, you can check if it's a list. It the first element of a list is a list, then it is two dimensional. Like this:
Code
ls = [[1,2],[3,4]]
if type(ls[0]) is list:
    print ("Is 2D")
else:
    print ("Not 2D")
Thanks for the feedback. I'm going to try your way Import. I like the ghetto method btw Skyla Blue.
(Mar 1, 2014 03:33 PM)ImportUsername Wrote:  You can use type() to check the type of something. If you check the first item in the list, you can check if it's a list. It the first element of a list is a list, then it is two dimensional. Like this:
Code
ls = [[1,2],[3,4]]
if type(ls[0]) is list:
    print ("Is 2D")
else:
    print ("Not 2D")

That or you could use isinstance:
PHP Code

<?php 
a 
= [[1,2,3],[4,5,6]]
print 
isinstance(a[0],list) 

And if you wanted to check if any of the items are a list:
PHP Code

<?php 
a 
= [[1,2,3],[4,5,6]]
print 
any(map(lambda x:isinstance(x,list),a)) 
Is there any reason to use either type or isinstance over the other.
(Mar 1, 2014 06:42 PM)_UserName_ Wrote:  Is there any reason to use either type or isinstance over the other.

Take a look at this: https://stackoverflow.com/questions/1549...-in-python

(also maybe try a quick google search next time? 😝)
The irony is that I posted here and then looked online and found that exact same page. I guess Google is as fast as a forum. 🤣


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by gurlhackerclubMay 19, 2020 05:18 PM 8 259 May 19, 2020 05:18 PM
Last Post: k1r3n
[Java] by TheBlueSuedeMar 16, 2019 01:46 PM 3 188 Mar 16, 2019 01:46 PM
Last Post: lockhead
[C] by TralenSep 9, 2017 05:13 PM 7 211 Sep 9, 2017 05:13 PM
Last Post: 0xDEAD10CC