-3

我最近一直在学习一些列表,我想制作一个程序,询问应该列出的元素的 x 数量,然后询问列表中的元素,以及列表中是否有 x 元素,而循环中断并打印出元素以及多少那里的元素就是我的代码:


    num = input("How many numbers you want to put into a list?: ")

while True:
    list = [input()]
    if len(list) == num:
        break


def get_number_of_elements(list):
    count = 0
    for element in list:
        count = count + 1
    return count



print(get_number_of_elements(list))


print(list)

当我运行代码时,它仍然要求列表中的元素,我不知道该怎么做。

4

1 回答 1

0

如果您想坚持自己编码的方式:

# make the input into an int because you want to compare it with a length in the while loop
num = int(input("How many numbers you want to put into a list?: "))
# don't name your variables after a type. 'list' is already the name of a type
l = [input("Enter number: ")]

# while the length of the list is not equal to the num, keep prompting
while len(l) != num:
    # add on to the list 'l'. Before you were creating a new list every loop
    l.append(input("Enter next number: "))

def get_number_of_elements(l):
    count = 0
    for element in l:
        count = count + 1
    return count

print(get_number_of_elements(l))
print(l)

相反,您可以这样做:

l = []
for _ in range(int(input("How many numbers you want to put into a list?: "))):
    l.append(int(input("Enter number: ")))

print("Number of elements:", len(l))
print("Here's your list:", l)
于 2021-04-01T22:46:05.573 回答