Accessing items in nested tuples

Mensanator mensanator at aol.com
Tue Apr 21 16:31:49 EDT 2009


On Apr 21, 3:03 pm, alex <ale... at bluewin.ch> wrote:
> Hello everybody
> I am able to access the data in a tuple via a for loop (see example
> below).
>
> #!/usr/bin/env python
>
> class Test():
>     def Data(self):
>         return ("aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh")
> #        return (("aa", ("bb", "cc", "dd")), ("ee", ("ff", "gg",
> "hh")), ("ii", ("jj", "kk", "ll")))
>
>     def Process(self):
>         for eachData in self.Data():
>             print "Printing %s" % eachData
>
> def main():
>     print "Start processing data"
>     prtData=Test()
>     prtData.Process()
>     print "Stop processing data"
>
> if __name__ == '__main__':
>     main()
>
> However I do not find out how to access data items in a nested tuple
> of
> the type (("aa", ("bb", "cc", "dd")), ("ee", ("ff", "gg", "hh")),...).
> In fact I am trying to refactor a simple GUI basing on an example
> in "wxPython In Action", "Listing 5.5 A refactored example" where the
> menues
> are described in the way
>
>     def menuData(self):
>         return (("&File",
>                 ("&Open", "Open in status bar", self.OnOpen),
>                 ("&Quit", "Quit", self.OnCloseWindow)),
>                 ("&Edit",
>                 ("&Copy", "Copy", self.OnCopy),
>                 ("C&ut", "Cut", self.OnCut),
>                  ...)))
>
>     etc...
>
> But I can not get the example running and I can't reprogram the
> example to get it running for my case.
>
> In IDLE I can print the individual tuples but not the items within.
>
> IDLE 1.2.1>>> data=(("aa", ("bb", "cc", "dd")), ("ee", ("ff", "gg", "hh")), ("ii", ("jj", "kk", "ll")))
> >>> print data[0]
>
> ('aa', ('bb', 'cc', 'dd'))>>> print data[1]
>
> ('ee', ('ff', 'gg', 'hh'))
>
> >>> etc...
>
> I would like to be able to access the dataitem "aa" or "bb", "cc",
> "dd" individualy.
> For sure I am most probably missing something which is evident, maybe
> can anybody help?

>>> for i in data:
	print i[0],
	for j in i[1]:
		print j,


aa bb cc dd ee ff gg hh ii jj kk ll

>>> print data[0]
('aa', ('bb', 'cc', 'dd'))
>>> print data[0][0]
aa
>>> print data[0][1][0]
bb
>>> print data[0][1][1]
cc



> Thanks Alex




More information about the Python-list mailing list