我想获取不重复的最大字符串数的子列表。
下面的代码说集合是不可散列的,这很有意义(TypeError: unhashable type: 'set'
),但我找不到解决这个问题的方法。
from collections import Counter
mylist = [{'task'}, {'task', 'time', 'element'}, {'task', 'current', 'time', 'element'}, {'task', 'element'}, {'task'}, {'task'}, {'task', 'element'}, {'task', 'element'}, {'task', 'element'}, {'task', 'push', 'stack', 'element'}]
find_max_lists = max(k for k,v in Counter(mylist).items() if v>1)
输入
[{'task'}, {'task', 'time', 'element'}, {'task', 'current', 'time', 'element'}, {'task', 'element'}, {'task'}, {'task'}, {'task', 'element'}, {'task', 'element'}, {'task', 'element'}, {'task', 'push', 'stack', 'element'}]
输出
[{'task', 'current', 'time', 'element'},{'task', 'push', 'stack', 'element'}]
输入
[{'task'}, {'task', 'time', 'element'}, {'task', 'current', 'time', 'element'}, {'task', 'element'}, {'task'}, {'task'}, {'task', 'element'}, {'task', 'element'}, {'task', 'element'}, {'task', 'current', 'time', 'element'}]
输出
[{'task', 'current', 'time', 'element'}]
答案 0 :(得分:2)
您可以在没有public static class EventHubCSharpFunc
{
[FunctionName("EventHubCSharpFunc")]
public static async Task Run([EventHubTrigger("containertestevthub", Connection = "EventGridPerfEventHun_RootManageSharedAccessKey_EVENTHUB")] EventData[] events, ILogger log)
{
var exceptions = new List<Exception>();
foreach (EventData eventData in events)
{
try
{
string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
// Replace these two lines with your processing logic.
log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
await Task.Yield();
}
catch (Exception e)
{
// We need to keep processing the rest of the batch - capture this exception and continue.
// Also, consider capturing details of the message that failed processing so it can be processed again later.
exceptions.Add(e);
}
}
// Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.
if (exceptions.Count > 1)
throw new AggregateException(exceptions);
if (exceptions.Count == 1)
throw exceptions.Single();
}
}
的情况下进行操作。由于列表包含集合,并且集合中不包含重复项,因此只需检查输入列表中长度最大的set-item,然后创建另一个列表,使其长度与最大长度匹配。
是这里:
Counter
输出:
max_len = len(sorted(mylist, key = lambda x: len(x), reverse = True)[0])
output = [k for k in mylist if len(k)==max_len]
# For the second case where the final list may contain same set-item
uniq_list = [set(x) for x in set(tuple(x) for x in output)]