从列表中的元组获取特定值

时间:2013-03-26 05:50:00

标签: list python-2.7 tuples

我有一个像这样的列表

tails = {(1, 352, 368), (2, 336, 368), (3, 320, 368)}

其中第一个值是尾数,第二个是x位置,第三个是y位置。后来在我的代码中,我有

for item in tail:
    pygame.draw.rect(windowSurface, RED, (xposition, yposition, 16, 16))

如何从特定元组中获取第二个和第三个值?

1 个答案:

答案 0 :(得分:0)

由于你正在学习python基础知识,我将展示几种不同的方法(尽管有python的“应该有一个 - 最好只有一个 - 显而易见的方法”):

for item in tails:
    xposition = item[1]  # get item by index
    yposition = item[2]
    pygame.draw.rect(windowSurface, RED, (xposition, yposition, 16, 16))

for item in tails:
    ( xposition, yposition ) = item[1:]  # tuple assignment
    pygame.draw.rect(windowSurface, RED, (xposition, yposition, 16, 16))

for tail_num, xposition, yposition in tails:  # tuple assignment in for-loop
    pygame.draw.rect(windowSurface, RED, (xposition, yposition, 16, 16))

# prepare args using list comprehension
rect_args_list = [ tuple(item[1:]) + ( 16, 16) for item in tails ]
for rect_args in rect_args_list:
    pygame.draw.rect(windowSurface, RED, rect_args)