简体   繁体   中英

(Python) How to stop adding strings to list after a certain point?

I'm trying to make a list with random numbers between 1 and 6 but only to a point where there are two 6's next to each other.

This is what I've tried to do:

numbers = []

while numbers[-1] != "6" and numbers[-2] != "6":
    numbers.append(random.randint(1,6))

but i gives me this error:

Exception has occurred: IndexError
list index out of range
  File "C:...\sestka.py", line 5, in <module>
    while numbers[-1] != "6" and numbers[-2] != "6":

I also did this which works, but it's kinda scuffed and I want to do it the right way:

numbers = []

for i in range(1000000):
    numbers.append(random.randint(1,6))
    if numbers[-1] == 6 and numbers[-2] == 6:
        break  

The IndexError that is occurring is because you have an empty list initially. Using the index -1 will give the last element in the list, but if there are no elements in the list, the IndexError is raised.

import random
# Initialize numbers to have two values
numbers = [random.randint(1,6), random.randint(1,6)]

# Check the last two values to ensure one is not a 6
while numbers[-2] != 6 or numbers[-1] != 6:
    numbers.append(random.randint(1,6))

# The loop will break when the last two elements are 6, resulting in [..., 6, 6]
print(numbers)

Your first example is on the right track, but you need to add another loop condition that keeps going if the list has fewer than two items:

numbers = []
while len(numbers) < 2 or numbers[-1] + numbers[-2] != 12:
    numbers.append(random.randint(1,6))
import random
random_list = [random.randint(1,6) for x in range(0,100)]

new_list = list()
iterator = 0
for x in range(len(random_list)):
    if random_list[iterator] == 6 & random_list[iterator + 1] == 6:
        for x in range(iterator+2):
            new_list.append(random_list[x])
        break
    else:
        iterator+=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM