在不使用for循环的情况下过滤嵌套列表?

时间:2018-06-16 10:25:32

标签: python-3.x list filter nested

您知道我是否可以过滤嵌套列表以仅返回每个子列表中的第二个值?我可以使用for循环来做,只是想知道是否可以使用过滤方法?

import pygame, sys
from pygame.locals import *
DISPLAYSURF = pygame.display.set_mode((1280, 720))


padX = 310
padY = 680
dotX = 150
dotY = 150
dotMX = -1
dotMY = -1
lives = 5


def main(padX, padY, dotX, dotY, dotMX, dotMY, lives):
    pygame.init()

    pygame.display.set_caption('Breakout')
    while lives != 0:
        DISPLAYSURF.fill(pygame.Color(0,0,0))
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                padX = event.pos[0]-75

            if padX < 3:
                    padX = 3

            elif padX > 1127:
                    padX = 1127

        pygame.draw.rect(DISPLAYSURF, pygame.Color(0, 0, 255),(padX, padY, 150, 30))

        dotX += dotMX
        dotY += dotMY

        dotMX, dotMY, lives = colis(dotX, dotY, dotMX, dotMY, padX, padY, lives)  # This line

        pygame.display.update()

def colis(dotX, dotY, dotMX, dotMY, padX, padY, lives):
    if dotY >= 720 - 30:
        lives -= 1

    #hor colis
    if dotX <= 0 + 20:
        if dotMX == 1:
            dotMX = -1
        else:
            dotMX = 1
    elif dotX >= 1280 - 20:
        if dotMX == 1:
            dotMX = -1
        else:
            dotMX = 1
    #vert colis
    if dotY <= 0 - 20:
        if dotMY == 1:
            dotMY = -1
        else:
            dotMY = 1
    elif dotY >= 720 - 20:
        if dotMY == 1:
            dotMY = -1
        else:
            dotMY = 1
    #pad colis
    if dotX >= padX and dotX <= padX + 150 and dotY == 665:
        if dotMY == 1:
            dotMY = -1
        else:
            dotMY = 1
    pygame.draw.circle(DISPLAYSURF, pygame.Color(255,0,0), (dotX, dotY), 20)

    return dotMX, dotMY, lives # This line


main(padX, padY, dotX, dotY, dotMX, dotMY, lives)

返回:

weather_data = [['1', 'sunny'], ['2', 'rainy'], ['3', 'sunny']]

2 个答案:

答案 0 :(得分:1)

如何使用列表理解:

values = [x[1] for x in weather_data]
print (values)

答案 1 :(得分:1)

假设您在问题中选择的snake_case意味着Python,请尝试map函数:

weather_data = [['1', 'sunny'], ['2', 'rainy'], ['3', 'sunny']]
result = list(map(lambda x: x[1], weather_data))
print(result)

如果不是Python,许多其他语言的语法略有不同:

https://en.wikipedia.org/wiki/Map_(higher-order_function)#Language_comparison