![]() |
|
[Python] Single vs multi-dimensional array - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [Python] Single vs multi-dimensional array (/showthread.php?tid=4090696) |
Single vs multi-dimensional array - _UserName_ - Mar 1, 2014 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", "."]] * - Skyla Blue - Mar 1, 2014 (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? A really really ghetto way of doing it could be: Code if str(array2).count("[") > 1 and str(array2).count("],") > 1:* - ImportUsername - Mar 1, 2014 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]]* - _UserName_ - Mar 1, 2014 Thanks for the feedback. I'm going to try your way Import. I like the ghetto method btw Skyla Blue. * - glob - Mar 1, 2014 (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: That or you could use isinstance: PHP Code And if you wanted to check if any of the items are a list: PHP Code * - _UserName_ - Mar 1, 2014 Is there any reason to use either type or isinstance over the other. * - ImportUsername - Mar 1, 2014 (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/1549801/differences-between-isinstance-and-type-in-python (also maybe try a quick google search next time? 😝) * - _UserName_ - Mar 1, 2014 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. 🤣 |