在python中为-loop创建唯一名称列表 [英] create lists of unique names in a for -loop in python

查看:142
本文介绍了在python中为-loop创建唯一名称列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在for循环中创建一系列具有唯一名称的列表,并使用索引来创建名称。这是我想做的事

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $我在x:

list_i = []

我想创建空列表,如

  lst_100 = [],lst_2 = [] lst_300 = [] .. 

任何帮助?

解决方案

不要做动态命名的变量。这使得难以编程。而是使用字典:

  x = [100,2,300,4,75] 
dct = {}
for i in x:
dct ['lst_%s'%i] = []

print(dct)
#{'lst_300':[], 'lst_75':[],'lst_100':[],'lst_2':[],'lst_4':[]}


I want to create a series of lists with unique names inside a for-loop and use the index to create the liste names. Here is what I want to do

x = [100,2,300,4,75]

for i in x:

  list_i=[]

I want to create empty lists such as

lst_100 = [], lst_2 =[] lst_300 = []..

any help?

解决方案

Don't make dynamically named variables. It makes it hard to program with them. Instead, use a dict:

x = [100,2,300,4,75]
dct = {}
for i in x:
    dct['lst_%s' % i] = []

print(dct)
# {'lst_300': [], 'lst_75': [], 'lst_100': [], 'lst_2': [], 'lst_4': []}

这篇关于在python中为-loop创建唯一名称列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆