如何解决如何在Python中将字典拆分成多个字典的列表,所有字典的大小均为N
假设我有一个简单的Python字典,如下所示:
using apiPQR.Contexts;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System;
namespace apiPQR
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,ValidateAudience = false,ValidateLifetime = true,ValidateIssuerSigningKey = true,IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(Configuration["jwt:key"])),ClockSkew = TimeSpan.Zero
};
}
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
我的目标是将这本词典分成一系列词典,所有词典的大小都为N,但最后一个词典的大小除外,如果词典中没有足够的元素,则最后一个词典的大小可能小于N。所以N = 2将产生:
{'location1': [1],'location2': [1],'location3': [1],'location4': [1],'location5': [1]}
当N = 3时会产生:
[{'location1': [1],'location2': [1]},{'location3': [1],'location4': [1]},{'location5': [1]}]
我已经尝试过,但是找不到解决方法。请注意,每个切片/批次中的位置对我来说都无关紧要,只要它们在切片之间均等分布即可。
解决方法
尝试这样的事情:
n = 2 # the desired # of parts
items = list(d.items())
y = [dict(items[x:x+n+1]) for x in range(0,len(d),n+1)]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。