【问题标题】:Get unique values from a for loop by filtering duplicates [duplicate]通过过滤重复项从 for 循环中获取唯一值 [重复]
【发布时间】:2020-10-08 17:53:25
【问题描述】:

目标:我想得到一个唯一值的列表。该列表应删除重复项,理想情况下应根据编号对它们进行排序

我有以下 JSON 文件。

{ "words" : [{"id":598,"tags":[104,65],"langs":[1]},{"id":597,"tags":[104,65],"langs":[1]},{"id":596,"tags":[20,30],"langs":[1]}]}

在我的脚本中,我有以下代码:

count = 0
tags = []
for index in data['words']: 
    count += 1
    tags.append(index["tags"])

这将打印以下代码:

print tags
# result: [[104, 65], [104, 65], [20, 30]]

我想要实现的是获得一个唯一的数字列表。所以我最终会遇到这种情况:

# result [20,30,65,104]

在这种情况下,双精度值被删除。有人可以帮助我进入这个方向吗?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

简单的方法是使用set 来收集不同的标签,可能是这样的:

tag_set = set()
for index in data['words']: 
    count += 1
    for t in index["tags"]:
        # if the tag 't' already exists in 'tag_set', it will NOT
        # be added again, that is the built-in behavior of a set.
        tag_set.add(t)

print(len(tag_set))
print(list(sorted(tag_set)))

【讨论】:

  • 你可以跳过第二个循环,直接做 tag_set.update(index["tags"])... 或者 set-comp tag_set = {t for index in data['words'] for t in index['tags']}
猜你喜欢
  • 1970-01-01
  • 2014-07-30
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多