【问题标题】:Removing duplicates from python array从python数组中删除重复项
【发布时间】:2021-08-15 07:20:20
【问题描述】:

编写一个 Python 程序,用户可以在其中输入一个值列表和这些值 然后以相同的顺序打印值但不重复。 使用标记“DONE”结束输入列表。

我无法让用户输入他们自己的字符串,我尝试了检查下面的代码。

示例 I/O

Enter strings (end with DONE):
the
old
man
and
the
sea
DONE

Sample Output
Unique list:
the
old
man
and
sea

我的代码:

a = ["Hello","Huitahani","good","Hello","apple","donkey","zebra","apple"]
a = set(a)
result = [] 
for item in a: 
    if item not in a: 
        a.add(item) 
        result.append(item) 
print(a) 

【问题讨论】:

  • 只检查输入是否已经在列表中,如果不是则追加它。 (并为您的下一个问题付出更多努力。)
  • 我未能让用户成为用户插入自己的输入
  • 使用 input() 从用户那里获取输入。如果您在geeksforgeeks.org/taking-input-in-python之前从未使用过 input() ,请检查此内容@
  • 所以应该是 a = input() ?
  • 在下面查看我的答案。

标签: python arrays python-3.x list python-requests


【解决方案1】:

看看这个sn-p:

a = []
item = input("Enter string (end with DONE):")
while not item == "DONE" : 
    if item not in a: 
        a.append(item)
    item = input("Enter next string (end with DONE):")
print(a)

【讨论】:

    【解决方案2】:

    我对您的代码做了一些更改:

    a = ["Hello","Huitahani","good","Hello","apple","donkey","zebra","apple"]
    # don't convert to set as it can mess up the order
    result = [] 
    for item in a: 
        if item not in result: # check if there is already one in result
            result.append(item) 
    
    print(result) # print the new list instead of the original list
    

    输出:['Hello', 'Huitahani', 'good', 'apple', 'donkey', 'zebra']

    如果你想获得用户输入,你可以试试这个:

    print('Enter strings (end with DONE):')
    input_list = []
    while True:
        user_input = input()
        if user_input == 'DONE':
            break
        input_list.append(user_input)
    

    【讨论】:

      猜你喜欢
      • 2012-12-14
      • 2011-06-29
      • 2011-01-04
      • 2020-01-24
      • 2013-08-03
      相关资源
      最近更新 更多