Не удается точно сопоставить данные из списка с целым числом

#python #list #if-statement #turtle-graphics

#python #Список #if-оператор #черепаха-графика

Вопрос:

Я пытаюсь вызвать поиск по списку с if утверждениями, а затем добавить значения в координату, которую я могу вызвать для рисования объекта в turtle. Подобные решения приветствуются, но я действительно хотел бы знать, где я ошибаюсь в своих размышлениях здесь:

 fixed_data_set_01 = [['Competitor A', 'Right'],
                     ['Competitor A', 'Down'],
                     ['Competitor A', 'Down'],
                     ['Competitor A', 'Left'],
                     ['Competitor A', 'Up']]


def list_searcher():

    global fixed_data_set_01
    d = len(fixed_data_set_01)
    f = 0 # looping variable to search through index
    y = 0 # defining y coord
    x = 0 # defining x coord
    
    for lister in range(d):
        
        print(fixed_data_set_01[f])
        f = f   1
        p = fixed_data_set_01[f]
        
        if 'Up' in p:#if up is in the move set add value to y coord for competitor
            y = y   90
            print(y,x)# testing
                 return y
    
        if 'Down' in p:#if down is in the move set add value to y coord for competitor
            y = y - 90
            print(y,x)# testing
                return y

        if 'Left' in p:#if left is in the move set add value to x coord for competitor
            x = x - 120
            print(y,x)
                return x
        
        if 'Right' in p:#if right is in the move set add value to x coord for competitor  
            x = x   120
            print(y,x) # testing 
                return x
        
list_searcher()
  

Комментарии:

1. извините, я довольно новичок в этом, если это поможет мне понять, что мне не нужен возврат после каждого оператора if.

Ответ №1:

Мне трудно разобраться в вашем коде и объяснении. Лучшее, что я мог понять, это то, что набор данных должен генерировать путь, по которому следует конкурент, поэтому я реализовал это ниже:

 from turtle import Screen, Turtle

fixed_data_set_01 = [
    ['Competitor A', 'Right'],
    ['Competitor A', 'Down'],
    ['Competitor A', 'Down'],
    ['Competitor A', 'Left'],
    ['Competitor A', 'Up'],
]

def list_searcher(competitor, data_set):

    path = [(0, 0)]  # starting coordinates

    for who, *directions in data_set:

        if who != competitor:
            continue

        x, y = path[-1]

        if 'Up' in directions:  # if Up is in the set add, value to y coord
            path.append((x, y   90))
        elif 'Down' in directions:  # if Down is in the set, subtract value from y coord
            path.append((x, y - 90))
        elif 'Left' in directions:  # if Left is in the set, subtract value from x coord
            path.append((x - 120, y))
        elif 'Right' in directions:  # if Right is in the set, add value to x coord
            path.append((x   120, y))

    return path

screen = Screen()

path = list_searcher('Competitor A', fixed_data_set_01)

turtle = Turtle()

for position in path:
    turtle.goto(position)

screen.exitonclick()
  

введите описание изображения здесь

Если это не так, предоставьте больше кода и объяснений того, что вы пытаетесь сделать.