如何从Python中的列表创建循环列表?

时间:2017-07-30 03:32:20

标签: python list slice itertools circular-list

我是Python的新手,我需要一个循环列表。我有一个包含5个标签的列表:

taglist

我有另一个单调增加值的列表:

list

我想使用listnewtaglist = ["faint", "shocking", "frosty", "loved", "sadness","faint", "shocking"] 的长度创建另一个列表。如果public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); //if (env.IsDevelopment()) builder.AddUserSecrets<Startup>(); builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddOptions(); services.Configure<Config>(Configuration.GetSection("AppSettings")); services.AddSingleton<IConfiguration>(Configuration); services.AddDbContext<MemoryContext>( options => options.UseSqlServer(Configuration.GetConnectionString("Database"), b => b.MigrationsAssembly("MemoryServer"))); services.AddIdentity<User, IdentityRole<Guid>>() .AddEntityFrameworkStores<MemoryContext>() .AddDefaultTokenProviders(); // Add framework services. services.AddMvc(); services.ConfigureApplicationCookie(options => { options.ExpireTimeSpan = TimeSpan.FromDays(150); options.LoginPath = "/api/auth/login"; options.LogoutPath = "/api/auth/logout"; }); services.Configure<IdentityOptions>(options => { options.Password.RequireDigit = true; options.Password.RequiredLength = 8; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = true; options.Password.RequireLowercase = true; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); options.Lockout.MaxFailedAccessAttempts = 10; options.User.RequireUniqueEmail = true; options.SignIn.RequireConfirmedEmail = false; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var supportedCultures = new[] { new CultureInfo("en-US"), }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); else app.UseExceptionHandler("/Home/Error"); app.UseAuthentication(); app.UseMvcWithDefaultRoute(); } } 有7个项目,我想要一个新的标签列表,如下所示。

public class MemoryContext : IdentityDbContext<User, IdentityRole<Guid>, Guid>
{
    public DbSet<Lesson> Lessons { get; set; }
    public DbSet<LessonAssignment> Assignments { get; set; }
    public DbSet<Review> Reviews { get; set; }
    public DbSet<UserList> UserLists { get; set; }
    public DbSet<Language> Languages { get; set; }

    public MemoryContext(DbContextOptions options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<UserListEntry>().HasKey(a => new {a.OwnerId, a.LessonId});
        builder.HasDbFunction(typeof(MemoryContext).GetMethod(nameof(Levenshtein)), funBuilder => {});
    }

    protected override void OnConfiguring(DbContextOptionsBuilder builder)
    {
        base.OnConfiguring(builder);
        builder.EnableSensitiveDataLogging();
    }

    public static int Levenshtein(string s1, string s2, int max) { throw new NotImplementedException(); }
}

这个列表将继续像圆​​形填充一样。我怎么能这样做?

已解决:感谢所有在此帖中回答的人。现在我很困惑地选择了答案。 :(每个人看起来都很好。虽然我使用过的那个更简单。

5 个答案:

答案 0 :(得分:10)

最简单的方法是使用专为此特定目的而设计的itertools.cycle

>>> from itertools import cycle, islice
>>> baselist = [1,2,3,4,5,6,7]
>>> taglist = ["faint", "shocking", "frosty", "loved", "sadness"]
>>> list(islice(cycle(taglist), len(baselist)))
['faint', 'shocking', 'frosty', 'loved', 'sadness', 'faint', 'shocking']

另一种方法是将列表相乘(重复)以使其足够大,然后切掉任何多余的列表:

>>> baselist = [1,2,3,4,5,6,7]
>>> taglist = ["faint", "shocking", "frosty", "loved", "sadness"]
>>> n = len(baselist)
>>> (taglist * -(n // -len(taglist)))[:n]
['faint', 'shocking', 'frosty', 'loved', 'sadness', 'faint', 'shocking']

双重否定用于将场地划分转换为上限划分,只要有剩余部分就会进行舍入。这确保了列表乘法总是至少提供所需数量的元素。

答案 1 :(得分:3)

另外,在python list是内置函数时,不要使用list作为变量名。

taglist = ["faint", "shocking", "frosty", "loved", "sadness"]
print(len(taglist))
list_ = [1,2,3,4,5,6,7]
print(len(list_))

diff = len(list_) - len(taglist)

for i in range(0, diff):
  taglist.append(taglist[i])
print(taglist)

答案 2 :(得分:2)

可以使用模运算符生成

newtaglist以确保索引在范围

taglist = ["faint", "shocking", "frosty", "loved", "sadness"]
num_list = [1,2,3,4,5,6,7]
newtaglist = [taglist[i % len(taglist)] for i in xrange(len(num_list))]

产量:

  

['微弱','令人​​震惊','冷淡','爱','悲伤','微弱','令人​​震惊']

运行here

答案 3 :(得分:2)

其中n是所需的长度:

from itertools import cycle
infiniteTagList = cycle(taglist)
[next(infiniteTagList) for i in range(n)]

或者您可以使用Raymond的

建议
list=[]
for num in range (1,10): #Request 10 numbers (it can't be zero)
    num=int (input("Add 10 digits:"))
    list.append (num)
    while num != 0:
        print ("The number is valid.")

答案 4 :(得分:2)

乘以加切片:

>>> taglist = ['a', 'b', 'c', 'd', 'e']
>>> length = 13
>>> 
>>> q, r = divmod(length, len(taglist))
>>> taglist * q + taglist[:r]
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c']