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

时间:2015-11-19 09:08:03

标签: python list python-3.x

我正在编写一个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 :(得分: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 s,如下一节所示。

重构代码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}

答案 1 :(得分: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,您可能还想引入警告。
  4. 更多Pythonic版本

    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
    

答案 2 :(得分: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()

答案 3 :(得分:0)

使用sets的另一种方式,交叉运算符代表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

答案 4 :(得分:0)

可能不是很好的解决方案,但可以这样做:

{{1}}