ValueError: list.remove (x): x нет в списке ошибок, как исправить? - PullRequest
0 голосов
/ 08 апреля 2019

У меня есть некоторый код, который проходит цикл for и должен выдавать мне 9 строк и 9 столбцов кнопок в окне tkinter. На этих кнопках должно быть случайное число от 1 до 9. Но я не хочу, чтобы одно и то же число в одном столбце и строке было одинаковым.

Чтобы добиться этого, я пробовал .pop [] и .remove () и del, но ни один из них не работал должным образом. Я получаю сообщение об ошибке row1.remove ("4") ValueError: list.remove (x): x отсутствует в списке. И есть 2 одинаковых номера в одном ряду, когда я пытался удалить этот номер. Может кто-нибудь помочь, пожалуйста?

import tkinter as tk
import random
row1 = ["1","2","3","4","5","6","7","8","9"]
col1 = ["1","2","3","4","5","6","7","8","9"]
button = ["1","2","3","4","5","6","7","8","9"]
random.shuffle(button)
root = tk.Tk()
i = 0
for x in range(9):
    for y in range(9):
        number = random.choice(button)
        btn = tk.Button(text=number, bg="white", activebackground="black", 
width=2)
        btn.grid(row=y, column=x)
        i += 1
        print(number)
        if number == "1":
            row1.remove("1")
            col1.remove("1")
        elif number == "2":
            row1.remove("2")
            col1.remove("2")

Кстати, элиф доходит до числа 9. Я просто не хотел все это здесь.

Я ожидаю, что результатом будет сетка 9 x 9, содержащая случайное число в диапазоне от 1 до 9, и ни одно из чисел в строке и столбце не будет одинаковым.

1 Ответ

1 голос
/ 08 апреля 2019

Ниже скрипт со встроенным кодом многое объясняет.Поскольку ваша матрица 9x9, я использовал строки * columns = 81, потому что вы можете идентифицировать их все.Если только 9 значений, вы получите еще несколько двойников.Легко настроить с помощью регулировки unique_value.Наслаждайтесь простотой; P

import tkinter as tk
import random

rows       = 9
columns    = 9

unique_IDs = 9   # unique IDs per row. If value below e.g. rows 
                 # then backup button list is created to prevent
                 # an empty list below. Value larger than zero.

root = tk.Tk()
i = 0

# if matrix == unique IDs the amount (rows * columns)IDs is created.
if rows * columns == unique_IDs:

    # if unique IDs are smaller than row values below code 
    # compensates for it by taking total positions in rows as base.                          
    if unique_IDs < rows:
        button = [*range(1, ((rows) + 1))]
    else:
        button = [*range(1, ((unique_IDs) + 1))]

    random.shuffle(button)

    print ('random : %s' % button)   # checks if list random is truly random.

for x in range(rows):

    # if matrix != unique IDs the amount of unique_IDs is created.
    if (rows * columns) != unique_IDs:                      
        button        = [*range(1, ((unique_IDs) + 1))]

        random.shuffle(button)

        print ('random : %s' % button)   # checks if list random is truly random.

    for y in range(columns):

        # number = random.choice(button) # twice the shuffle dance? Nah!
        number = button.pop(0)           # just keep popping the soda at first number 
                                         # from the randomized button order list
                                         # while it gets smaller and smaller.

        btn = tk.Button(text=number, bg="white", activebackground="black", width=2)
        btn.grid(row=y, column=x)
        i += 1
        print(' x, y, value : (%s,%s), %s' % (x, y, number))  # output check!

        # likely obsolete code below this comment line.

        if number == "1":
            row1.remove("1")
            col1.remove("1")
        elif number == "2":
            row1.remove("2")
            col1.remove("2")

... snippet ... tk GUI code here ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...