webmaker
webmaker

Reputation: 466

how to access/lists in a tuple

I have a tuple where my_tuple[0] contains an integer and my_tuple[1] contains 3 lists. So

my_tuple[0]=11
my_tuple[1]= [[1,2,3], [4,5,6], [7,8,9]]
for tuple_item in my_tuple[1]:
    print tuple_item

How could I extract the lists from my_tuple[1] without using any external libraries (my current python interpreter has limitations)? I would like to be take the lists from the tuple and then create a dict of lists. Alternatively, I could do a list of lists

key=my_tuple[0]
#using the same key 
my_dict[key]= list1
my_dict[key]= list2
my_dict[key]= list3

#or

for tuple_item in my_tuple[1]: 
    list_of_lists.append(tuple_item)

Upvotes: 0

Views: 88

Answers (2)

aghast
aghast

Reputation: 15310

Based on your comment in response to @Gijs, it sounds like you've got a perfectly good data structure already. Nonetheless, here's another:

#python3
from collections import namedtuple
Point = namedtuple("Point", "x, y, z")
Triangle = namedtuple("Triangle", "number, v1, v2, v3")

# Here is your old format:
my_tuple = (11, [ [1,2,3], [4,5,6], [7,8,9] ])

v1 = Point(*my_tuple[1][0])
v2 = Point(*my_tuple[1][1])
v3 = Point(*my_tuple[1][2])
num = my_tuple[0]

new_triangle = Triangle(num, v1, v2, v3)

print(new_triangle)

Output is:

Triangle(number=11, v1=Point(x=1, y=2, z=3), v2=Point(x=4, y=5, z=6), v3=Point(x=7, y=8, z=9))

You can use new_triangle.num and new_triangle.v1 to access members, and you can use new_triangle.v3.z to access submembers.

But I'll bet it won't be long before you wish you could loop over the vertices...

Upvotes: 0

Gijs
Gijs

Reputation: 10891

You need to generate a key for each list. In this example, I use the index of each list:

my_tuple = [None, None]        # you need a list, otherwise you cannot assign values: mytuple = (None, None) is a tuple
my_tuple[0] = 11
my_tuple[1] = [[1,2,3], [4,5,6], [7,8,9]]

dict_of_lists = dict()

for i, tuple_item in enumerate(my_tuple[1]): 
    key = str(i)                      # i = 0, 1, 2; keys should be strings
    dict_of_lists[key] = tuple_item

dict_of_lists

>> {'0': [1, 2, 3], '1': [4, 5, 6], '2': [7, 8, 9]}

Upvotes: 1

Related Questions