列表的组合

时间:2019-01-08 22:09:39

标签: python python-3.x list

我正在尝试获取列表的所有组合,但是每次需要删除两个元素时,如何删除这些元素?

我试图做一个for循环两次,每次它删除两个元素,但是最后它没有恢复列表

indexes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for een in indexes:
    for twee in indexes:
        temp = indexes
        if een == twee:
            pass
        else:
            if een in temp:
                temp.remove(een)
            temp.remove(twee)

            print(temp)
        temp = indexes

我希望每次输出长度为9的列表,但列表会越来越短。 我得到的输出是:

[2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 3, 5, 6, 7, 8, 9, 10]
[2, 3, 5, 7, 8, 9, 10]
[2, 3, 5, 7, 9, 10]
[2, 3, 5, 7, 9]
[5, 7, 9]
[5, 9]

第一个列表正确,但是在下一个列表中,第一个列表不返回。我究竟做错了什么?同样在完成后,应等于1,然后再进行一次,在完成后应等于2。 这应该是输出

[2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 2, 4, 5, 6, 7, 8, 9, 10]
[0, 2, 3, 5, 6, 7, 8, 9, 10]
[0, 2, 3, 4, 6, 7, 8, 9, 10]
[0, 2, 3, 4, 5, 7, 8, 9, 10]
[0, 2, 3, 4, 5, 6, 8, 9, 10]
[0, 2, 3, 4, 5, 6, 7, 9, 10]
[0, 2, 3, 4, 5, 6, 7, 8, 10]
[0, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 4, 5, 6, 7, 8, 9, 10]

并且应该努力直到达到每种组合

1 个答案:

答案 0 :(得分:1)

#code till this for guessesTaken in range(1,11): print('Take a guess.') while True: try: guess = int(input()) break except ValueError: print('Please enter a number') continue #rest of your code 替换为import random print('Hello, What is your name?') name = input() print('Well, ' + name + ', I am thinking of a number between 1 and 1000, You have 10 guesses to figure it out. Good luck!') secretNumber = random.randint(1,1000) print('DEBUG: Secret number is ' + str(secretNumber)) #code till this for guessesTaken in range(1,11): print('Take a guess.') while True: try: guess = int(input()) break except ValueError: print('Please enter a number') continue #rest of your code if guess < secretNumber: print('Your guess is too low.') elif guess > secretNumber: print('Your guess is too high.') else: break #This condition is for the correct guess if guess == secretNumber: print('Good job ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses!') else: print('Too many guesses, The number I was thinking of was ' + str(secretNumber))