【发布时间】:2023-01-08 02:39:59
【问题描述】:
程序应该在区间内产生10个随机数 [1;3],将它们存储在一个列表中,并打印列表的内容 屏幕上!用户应该能够在 interval [1;3],程序应该删除所有出现的地方 从列表中删除这个数字,然后打印修改后的列表 屏幕上!
我尝试用两种方法运行以下程序,但它们没有产生我想要的最终列表。
第一次尝试:
import random
random_list=[]
number=0
deleted_number=0
final_list=[]
for i in range(10):
number=random.randint(1,3)
random_list.append(number)
print(random_list)
deleted_number=input('Give a number from 1 to 3, that you want to delete from the list.')
final_list = list(set(random_list) - set(deleted_number))
print('The new list without the deleted values:')
print(final_list)
第二次尝试:
import random
random_list=[]
number=0
deleted_number=0
final_list=[]
for i in range(10):
number=random.randint(1,3)
random_list.append(number)
print(random_list)
deleted_number=input('Give a number from 1 to 3, that you want to delete from the list.')
final_list = [item for item in random_list if item != deleted_number]
print('The new list without the deleted values:')
print(final_list)
提前谢谢你的帮助。
【问题讨论】:
-
“他们没有提供我想要的最终名单。” - 或许。我们不知道,因为您没有提供实际输出与预期输出。请注意,本着提供 minimal reproducible example 的精神,您应该从非随机列表开始。
标签: python