如何在元组中访问/列表

时间:2016-02-24 20:37:14

标签: python tuples

我有一个元组,my_tuple[0]包含一个整数,my_tuple[1]包含3个列表。所以

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

如何在不使用任何外部库的情况下从my_tuple[1]中提取列表(我当前的python解释器有局限性)?我想从元组中取出列表,然后创建一个列表的字典。或者,我可以列出一份清单

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)

2 个答案:

答案 0 :(得分:1)

您需要为每个列表生成一个键。在这个例子中,我使用每个列表的索引:

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]}

答案 1 :(得分:0)

根据你对@Gijs的回应,听起来你已经拥有了一个非常好的数据结构。尽管如此,还有另一个:

#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)

输出是:

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))

您可以使用new_triangle.numnew_triangle.v1来访问成员,也可以使用new_triangle.v3.z访问子成员。

但是我敢打赌,在你希望你能够绕过顶点之前很久......