【问题标题】:List remove duplicates列出删除重复项
【发布时间】:2023-03-20 18:10:01
【问题描述】:

for 循环中有一个删除所有重复项的功能,但它没有。 .upper 有时也不起作用。请帮忙。

from collections import OrderedDict
def ask():
  global x
  x = str(input("Enter your logical operation:"))
  x = x.split( )
  x = [x.upper() for x in x]
  return x

ask()

for i in range(0,len(x)):
  and_index = x.index("AND",i)
  n = list(OrderedDict.fromkeys(str(and_index)))
  print(n)

print(n)

【问题讨论】:

标签: python-3.x list duplicates uppercase


【解决方案1】:

首先,您甚至没有保存 ask() 函数的输出,而是在全局范围内提供它,这不是一个好习惯。

def ask():
  x = input("Enter your logical operation:")
  return list(map(str.upper, x.split()))

user_input = ask()

然后要简单地删除重复项,您可以将您的 list 转换为 set,这样做会松散我们列表的顺序,但会快速轻松地删除重复项

user_input = list(set(user_input))

如果您想保持用户输入的操作顺序,您可以使用OrderedDict

from collections import OrderedDict
user_input = list(OrderedDict.fromkeys(user_input))

【讨论】:

    【解决方案2】:

    从列表中删除重复的示例

    mylist = ["a", "b", "c", "a", "b"]
    newlist = list(set(mylist))
    print(newlist)
    

    输出:["a", "b", "c"]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 2020-09-12
      • 1970-01-01
      • 2016-03-03
      • 2014-09-30
      • 2021-02-09
      • 1970-01-01
      • 2022-10-15
      相关资源
      最近更新 更多