Python 如何将int输入与列表进行比较
编写一个Python程序,加载一个15个随机数范围为35的列表 – 50. 按升序显示列表A。然后得到一个数字X。将X与每个数字进行比较 元素,如果列表元素小于X,则将该元素替换为X。在…上 另一行,用X替换所有小于X的元素后,显示A的元素 我得到了随机列表,但我不知道如何将X与列表进行比较。请帮忙。到目前为止,这是我仅有的代码 随机输入 listA=[] i=15 对于rangei中的num: num=random.randint35,50 附子 A:,sortedlistA的打印元素 示例运行应如下所示: 产出1:A的要素:35 35 37 38 39 42 46 47 48 49 50 输入X:37 A的新元素:37 37 38 39 42 43 46 47 48 49 50Python 如何将int输入与列表进行比较,python,Python,编写一个Python程序,加载一个15个随机数范围为35的列表 – 50. 按升序显示列表A。然后得到一个数字X。将X与每个数字进行比较 元素,如果列表元素小于X,则将该元素替换为X。在…上 另一行,用X替换所有小于X的元素后,显示A的元素 我得到了随机列表,但我不知道如何将X与列表进行比较。请帮忙。到目前为止,这是我仅有的代码 随机输入 listA=[] i=15 对于rangei中的num: num=random.randint35,50 附子 A:,sortedlistA的打印元素 示例运
您可以编写类似这样的代码来迭代listA并检查该元素是否等于x
x = int(input("Set x: "))
对于listA中的元素:
如果元素==x:
通过
但是,问题是要用X替换该元素,因此,最好这样:
for i in range(len(listA)):
if listA[i] < x:
listA[i] = x
如果你试试这个怎么办
import random
listA = []
i = 15
for num in range(i):
num = random.randint(35, 50)
listA.append(num)
print("Elements of A (BEFORE): ", sorted(listA))
random_input = int(input("Write a number... > "))
# Here we search for j in listA
for j in listA:
# Then we compare it to the input and exclude the smaller ones
if j < random_input:
# We create a var which represents the position of the object in the list based on j
k = listA.index(j)
# And then we replace k place in the list with our random input
listA[k] = random_input
print("Elements of A (AFTER): ", sorted(listA))
随机输入
A=列表
对于我来说,范围15:
A.A.randint35,50
A.sortreverse=False
版画
X=输入写入一个要与之比较的数字:
对于我来说,范围15:
如果X>A[i]:
A[i]=X
版画
然后得到一个数字X——我把它理解为:获取输入。顺便说一句:为什么你从可能无法解决实际任务的代码开始?示例输出1:A的元素:35 35 37 38 39 42 43 47 48 49 50输入X:37 A的新元素:37 37 37 38 39 42 43 46 47 48 49 50 hear是示例输出,但我不知道how@Daniel最好将示例输出和输入添加到您的问题中把35s换成37,因为35比37小。谢谢男人们。这对我来说意义重大哈哈。解决方案极其复杂且效率低下,不应该指导任何初学者。我是Python的初学者。感谢您的指导@WolfI,我认为您的答案正在变好。我建议考虑反向参数,如果没有设置为True,它是多余的。还要添加一些文字来解释您的方法,即使问题看起来像是一个编码任务,您的答案也不必看起来只是完成了它。老实说,最初的问题在我看来似乎是假的:究竟如何使用随机函数容易而比较困难?
import random
listA = []
i = 15
for num in range(i):
num = random.randint(35, 50)
listA.append(num)
print("Elements of A (BEFORE): ", sorted(listA))
random_input = int(input("Write a number... > "))
# Here we search for j in listA
for j in listA:
# Then we compare it to the input and exclude the smaller ones
if j < random_input:
# We create a var which represents the position of the object in the list based on j
k = listA.index(j)
# And then we replace k place in the list with our random input
listA[k] = random_input
print("Elements of A (AFTER): ", sorted(listA))