【问题标题】:Remove all elements which occur in less than 1% and more than 60% of the list删除所有出现在列表中少于 1% 和超过 60% 的元素
【发布时间】:2013-08-09 00:11:58
【问题描述】:

如果我有这个字符串列表:

['fsuy3,fsddj4,fsdg3,hfdh6,gfdgd6,gfdf5',
'fsuy3,fsuy3,fdfs4,sdgsdj4,fhfh4,sds22,hhgj6,xfsd4a,asr3'] 

(大名单)

如何删除出现在少于 1% 和超过 60% 的字符串中的所有单词?

【问题讨论】:

  • 列表是您可以在这里使用的唯一数据结构吗?字符串如何填充到列表中
  • 字符串保证是逗号分隔的单词列表?而且您对那些逗号分隔的单词(例如“fsuy3”)感兴趣,而不是您显示的列表中的元素(例如,“fsuy3,fsddj4,...”)。
  • 在标题中你说“出现在列表中”和在问题正文中在“出现在字符串中”,你想要哪一个?

标签: python list


【解决方案1】:

您可以使用collections.Counter

counts = Counter(mylist)

然后:

newlist = [s for s in mylist if 0.01 < counts[s]/len(mylist) < 0.60]

(在 Python 2.x 中使用 float(counts[s])/len(mylist)


如果你说的是逗号分隔的词,那么你可以使用类似的方法:

words = [l.split(',') for l in mylist]

counts = Counter(word for l in words for word in l)

newlist = [[s for s in l if 0.01 < counts[s]/len(mylist) < 0.60] for l in words]

【讨论】:

  • 我不确定 OP 在寻找什么,但我不认为就是这样。看起来 OP 想要查看列表元素的逗号分隔子字符串。
【解决方案2】:

简单的解决方案

occurrences = dict()
for word in words:
  if word not in occurrences:
     occurrences[word] = 1
  else:
     occurrences[word] += 1

result = [word for word in words 0.01 <= occurrences[word] /len(words) <= 0.6]

【讨论】:

  • 而不是测试单词是否出现,您可以使用 default_dict。而不是 default_dict,您可以使用 Counter,它可以完成所有这些。
【解决方案3】:

我猜你想要这个:

    from collections import Counter,Set

# break up by ',' and remove duplicate words on each line
    st = [set(s.split(',')) for s in mylist]

# Count all the words
    count = Counter([word for line in st for word in line])

# Work out which words are allowed
    allowed = [s for s in count if 0.01 < counts[s]/len(mylist) < 0.60]

#For each row in the original list. If the word is allowed then keep it
    result = [[w for w in s.split(',') if w in allowed] for s in mylist]

    print result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多