如果数字不在列表中,则将其添加到数字列表 - Python

1 投票
5 回答
815 浏览
提问于 2025-05-10 15:03

我正在写一个Python程序,这个程序会从用户那里获取整数,并把这些整数添加到一个数字列表中,前提是这个数字还不在列表里。通常这并不难,但我不能使用in/not in操作符、index()函数或insert()函数来完成这个任务。

在我创建好列表后,我会问用户是否想要替换列表中的某些值。如果他们想替换,就需要获取要查找的值和替换的值。

同样,我不能使用in/not in操作符或index()函数来完成这个任务。

我的代码:

def figure_it_out(numbers_list):
    while True:
        number = int(input("Enter the number for the list: "))
        duplicate = False
        for val in numbers_list:
            if number == val:
                duplicate = True
                break

        if duplicate:
            print("Duplicate found")
        else:
            numbers_list.append(number)
            print("Added {}".format(number))

        answer = input("Would you like to add another number? (y/n): ")
        if answer == 'y':
            continue
        else:
            break

    return numbers_list

def replace_number(current_list):
    while True:
        answer = input("Would you like to replace a number? (y/n): ")

        if answer == 'y':
            count = 0
            num_replace = int(input("What number will you replace: "))
            duplicate = False
            for val in current_list:
                count += 1
                if num_replace == val:
                    duplicate = True
                    break

            if duplicate:
                replacment = int(input("Replace with: "))
                current_list[count - 1] = replacment
                print(current_list)
            else:
                print("There is no number in the list.")    
        else:
            break

    return current_list

def main():
    adding_list = []

    cur_list = figure_it_out(adding_list)

    print(cur_list)

    final_list = replace_number(cur_list)

    print("Your final list is: " + str(final_list))


main()

输出:

Enter the number for the list: 2
Added 2
Would you like to add another number? (y/n): y
Enter the number for the list: 3
Added 3
Would you like to add another number? (y/n): y
Enter the number for the list: 4
Added 4
Would you like to add another number? (y/n): y
Enter the number for the list: 5
Added 5
Would you like to add another number? (y/n): y
Enter the number for the list: 6
Added 6
Would you like to add another number? (y/n): n
[2, 3, 4, 5, 6]
Would you like to replace a number? (y/n): y
What number will you replace: 5
Replace with: 9
[2, 3, 4, 9, 6]
Would you like to replace a number? (y/n): y
What number will you replace: 6
Replace with: 8
[2, 3, 4, 9, 8]
Would you like to replace a number? (y/n): n
Your final list is: [2, 3, 4, 9, 8]

感谢大家的帮助!

相关文章:

  • 暂无相关问题
暂无标签

5 个回答

0

让我们稍微重构一下这个代码。

while True:
    new_item = int(input("Enter the number for the list: "))

    for existing_item in adding_list:
        if existing_item == new_item:  # see Note 1
            print("already in there.")
            break
    else:  # see Note 2
        adding_list.append(new_item)
        print("added")

    answer = input("Would you like to add another number? (yes or no): ")
    if answer == 'yes':
        continue  # see Note 3
    elif answer == 'no':
        return adding_list

注意事项

  1. 在原始代码中,你在条件第一次失败后就把一个项目添加到列表里。这是不对的,因为我们需要确保这个条件对列表中的所有元素都失败,而不仅仅是第一个。
  2. 这是一个 for... else 语句。else 部分会在循环正常结束时执行,只有在通过 break 终止循环的情况下才不会执行。
  3. 不需要特别的变量来继续循环。如果答案既不是 yes 也不是 no,你可能还想添加一个警告。

更符合Python风格的版本

while True:
    new_item = int(input("Enter the number for the list: "))
    item_exists = any(item == new_item for item in adding_list)
    if not item_exists:
        adding_list.append(new_item)

    answer = input("Would you like to add another number? (yes or no): ")
    if answer == 'yes':
        continue  # see Note 3
    elif answer == 'no':
        return adding_list
0

我对下面的代码进行了重构,运行时会产生以下输出:

Enter the number for the list: 1
Added 1
Would you like to add another number? (y/n): y
Enter the number for the list: 2
Added 2
Would you like to add another number? (y/n): y
Enter the number for the list: 2
Duplicate found
Would you like to add another number? (y/n): n
[1, 2]

总结

你需要遍历你手上的数字列表,检查每个数字,看是否有重复的。如果没有找到重复的,才把新数字加进去,这可能需要检查整个列表。

我做了一些以下的修改:

  • 去掉了你的 now 变量:这个变量其实不太需要,即使需要,也应该是布尔类型,而不是整数;
  • 在最后返回输出列表:在循环的主体外完成所有操作后再返回列表;
  • 去掉了起始的非空列表:没有必要传入一个已经有数字的列表,所以把 [0] 替换成了一个真正空的列表。

主要是修复了原来每次检查重复失败时都往列表里加数字的问题。

重构代码 1 - 使用 list

这是对你代码的一个小改动,基于上面的要点。

#!/usr/bin/python3 -B

def figure_it_out(numbers_list):
    while True:
        number = int(input("Enter the number for the list: "))
        duplicate = False
        for val in numbers_list:
            if number == val:
                duplicate = True
                break

        if duplicate:
            print("Duplicate found")
        else:
            numbers_list.append(number)
            print("Added {}".format(number))

        answer = input("Would you like to add another number? (y/n): ")
        if answer == 'y':
            continue
        else:
            break

    return numbers_list


if __name__ == '__main__':
    print(figure_it_out([]))

不过,我更喜欢使用 set,在下一部分会展示。

重构代码 2 - 使用 set(推荐)

这是我的推荐。使用 set 可以把查找重复的逻辑交给内置的数据结构处理。这样你的代码会更 简单,这总是好事。

#!/usr/bin/python3 -B

def figure_it_out(numbers_list):
    numbers_set = set(numbers_list)
    while True:
        try:
            number = int(input("Enter the number for the list: "))
            numbers_set.add(number)
        except ValueError as e:
            print(str(e))

        answer = input("Would you like to add another number? (y/n): ")
        if answer != 'y':
            break

    return list(numbers_set)

if __name__ == '__main__':
    print(figure_it_out([]))

此外,当获取用户输入时,你应该使用 try/except,如上所示。你让用户输入一个数字,并不意味着用户一定会输入一个数字,这样会导致程序崩溃,出现 ValueError。所以,你应该 永远不要信任 外部数据(例如用户输入、输入文件、网络数据包等)。这些都是潜在的攻击点。

小更新 - 替换现有集合元素

我试图用同样的方法替换列表中的一个值。[...] 你对这种情况有什么建议吗?

要替换一个元素,只需 discard 现有的元素,然后 add 你要替换的那个。请看我下面的例子:

>>> s = set([1, 2, 3, 4])
>>> s
{1, 2, 3, 4}
>>> s.discard(2)
>>> s
{1, 3, 4}
>>> s.add(6)
>>> s
{1, 3, 4, 6}
0

这可能不是最好的解决办法,但可以试试这样做:

def figure_it_out(adding_list):
now = 1
while now == 1:
    added = int(input("Enter the number for the list: "))

    adding_list.append(added)

    if adding_list.count(added) == 2:
        print "already there"
        adding_list.remove(added)
        return adding_list
    else:
        answer = input("Would you like to add another number? (yes or no): ")

        if answer == 'yes':
            now = 1
        elif answer == 'no':
            return adding_list
0

另一种方法是使用集合,用交集运算符来代替in这个关键字。

def get_numbers():
    numbers = set([])    
    while True:
        new_number = int(input("Enter the number for the list: "))
        if numbers & set([new_number]): # because we're not allowed to use in
            print('already in there')
        else:
            numbers.add(new_number)
            print('added')
        answer = input("Would you like to add another number? (yes or no): ")
        if answer == 'no':
            return list(numbers)

不过,通常来说,思考这个编程挑战的一个好方法是关注如何用你自己写的函数来替代那些你不能使用的语言部分。你可以简单地写一个函数is_in(element, list_),然后在你想用element in list_的地方使用它。以下任何一种方法都可以。

def is_in1(el, L):
    return bool(set(L) & set([el]))

def is_in2(el, L):
    return any(x == el for x in L)

def is_in3(el, L):
    for x in L:
        if x == el:
            return True
    return False

def is_in4(el, L):
    return L.count(el) > 0
0

最简单的方法就是使用 set 来处理去重的问题:

def figure_it_out(adding_list):
    now = 1
    while now == 1:
        added = int(input("Enter the number for the list: "))
        adding_list.append(added) 
        adding_list = list(set(adding_list))

        answer = input("Would you like to add another number? (yes or no): ")

        if answer == 'yes':
            now = 1
        elif answer == 'no':
            return adding_list

def main():
    adding_list = [0]

    cur_list = figure_it_out(adding_list)

    print(cur_list)

main()

撰写回答