簡體   English   中英

如何將int輸入與列表進行比較

[英]How to compare int input to a list

編寫一個 Python 程序,該程序將加載具有 15 個隨機數(范圍:35 - 50)的列表 A。 按升序顯示列表 A。 然后得到一個數字 X。將 X 與 A 的每個元素進行比較,如果列表元素小於 X,則將該元素替換為 X。在另一行,將所有小於 X 的元素替換為 X 后顯示 A 的元素。

我得到了隨機列表,但我不知道如何將 X 與列表進行比較。 請幫忙。 到目前為止,這是我擁有的唯一代碼。

import random

listA = []
i = 15
for num in range(i):
    num = random.randint(35, 50)
    listA.append(num)
print("Elements of A: ", sorted(listA))

示例運行應如下所示:

Output 1 : Elements of A : 35 35 37 38 39 39 42 43 46 47 47 48 49 50 50
Input X : 37 
New elements of A : 37 37 37 38 39 39 42 43 46 47 47 48 49 50 50
import random

A = list()

for i in range(15):
    A.append(random.randint(35, 50))

A.sort(reverse=False)
print(A)

X = int(input("Write a number to compare with: "))

for i in range(15):
    if X > A[i]:
        A[i] = X

print(A)

您可以編寫類似這樣的代碼來迭代 listA 並檢查該元素是否等於 x。

x = int(input("Set x: "))
for element in listA:
    if element == x:
        pass

但是,問題要求用 X 替換那個元素,所以,最好這樣:

for i in range(len(listA)):
    if listA[i] < x:
        listA[i] = x

通過這種方式,您將解決如果列表元素小於 X,則將該元素替換為 X

PS:如果 x 引發錯誤,因為它不能是 integer(例如:設置 x = hi),您可以在 int() 之前以這種方式檢查:

import sys

x = input("Set x: ")
if x.isdigit():
    x = int(x)
else:
    sys.exit(1)

如果你試試這個呢?

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM