【问题标题】:Sort Python list by first two characters and return the one that had more occurrences按前两个字符对 Python 列表进行排序并返回出现次数较多的列表
【发布时间】:2019-03-24 13:35:28
【问题描述】:
list = [('Confidence', 1), ('Malicious', 1), ('Gen3', 1), ('Filecoder', 1), ('Score', 1), ('Wanacrypt', 1), ('Engine', 1), ('Eqmtct', 1), ('Wannacryptor', 1), ('Aiqcm', 1), ('Wannacrypt', 1), ('Wcryg', 1), ('Cbvj', 1), ('Farfli', 1), ('Wanna', 1), ('Wisdomeyes', 1), ('Wannacry', 1), ('High', 1), ('Static', 1), ('Wcry', 1)]

return = [ WanaCrypt Wanna WannaCry WannaCrypt WannaCryptor ]

【问题讨论】:

  • 你试过什么?您可以发布您遇到的错误吗?
  • 每个元组中的整数是否应该意味着什么?
  • 请用MCVE 更新您目前尝试过的问题

标签: python list sorting


【解决方案1】:

如果我理解正确,您的元组列表中的数值不会影响您的结果,因为您只查找以最常见的前两个字符开头的字符串。

以下代码将执行此操作:

from collections import defaultdict, Counter

# Your list
tuples = [
    ('Confidence', 1), ('Malicious', 1), ('Gen3', 1), ('Filecoder', 1),
    ('Score', 1), ('Wanacrypt', 1), ('Engine', 1), ('Eqmtct', 1),
    ('Wannacryptor', 1), ('Aiqcm', 1), ('Wannacrypt', 1), ('Wcryg', 1),
    ('Cbvj', 1), ('Farfli', 1), ('Wanna', 1), ('Wisdomeyes', 1),
    ('Wannacry', 1), ('High', 1), ('Static', 1), ('Wcry', 1)
]

# Calculate which initial is more ocurrent
values = [t[0] for t in tuples]
initials = defaultdict(int)
for v in values:
    initials[v[:2]] += 1
initial_str = Counter(initials).most_common()[0][0]

# Creates a list with values that start with the most occurrent initial string 
results = [v for v in values if v.startswith(initial_str)]
print(results)

【讨论】:

    猜你喜欢
    • 2022-07-30
    • 1970-01-01
    • 2011-07-09
    • 2022-11-15
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多