Python 如果不在数组中,则将项目添加到数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18796331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:52:56  来源:igfitidea点击:

Add item into array if not already in array

pythonarrays

提问by Lucas

How can I insert item into the array if its not already there?

如果项目尚未存在,如何将项目插入到数组中?

This is what I tried:

这是我尝试过的:

    [..]
    k = []
    for item in myarray:
        if not item in k:
             print("Item is in array already.")
             k[] = item

采纳答案by Chad

Your code has the right idea but just use k.append(item)instead of k[] = item.

您的代码有正确的想法,但只需使用k.append(item)而不是k[] = item.

Also it is cleaner to say if item not in k:

也更干净地说 if item not in k:

回答by TerryA

k[] = itemis invalid syntax. All you need to do is just remove that line and use list.append()

k[] = item是无效的语法。您需要做的就是删除该行并使用list.append()

for item in myarray:
    if not item in k:
        print("Item is in array already.")
        k.append(item)

list.append()adds an item to the end of the list.

list.append()在列表的末尾添加一个项目。

回答by Patch Rick Walsh

If you don't care about the order of the items in the list, you can convert it to a set to filter out any duplicates.

如果您不关心列表中项目的顺序,则可以将其转换为集合以过滤掉任何重复项。

k = list(set(myarray))

k = list(set(myarray))

Or if k already contains something...

或者如果 k 已经包含一些东西......

k = [...]  # optionally non-empty array
k = list(set(k) | set(myarray))

What that does is convert both myarray and k into sets, and combines them so that the result is a unique list that containing the contents of both k and myarray.

这样做是将 myarray 和 k 都转换为集合,并将它们组合起来,这样结果就是一个包含 k 和 myarray 内容的唯一列表。