简体   繁体   English

如何将列表的每个元素分配给一个单独的变量?

[英]How to assign each element of a list to a separate variable?

if I have a list, say:如果我有清单,请说:

ll = ['xx','yy','zz']

and I want to assign each element of this list to a separate variable:我想将此列表的每个元素分配给一个单独的变量:

var1 = xx
var2 = yy
var3 = zz

without knowing how long the list is, how would I do this?在不知道列表有多长的情况下,我该怎么做? I have tried:我试过了:

max = len(ll)
count = 0
for ii in ll:
    varcount = ii
    count += 1
    if count == max:
        break

I know that varcount is not a valid way to create a dynamic variable, but what I'm trying to do is create var0 , var1 , var2 , var3 etc based on what the count is.我知道 varcount 不是创建动态变量的有效方法,但我想要做的是根据计数创建var0var1var2var3等。

Edit: :编辑::

Never mind, I should start a new question.没关系,我应该开始一个新的问题。

Generally speaking, it is not recommended to use that kind of programming for a large number of list elements / variables.一般来说,对于大量的列表元素/变量,建议使用那种编程。

However, the following statement works fine and as expected但是,以下语句按预期工作正常

a,b,c = [1,2,3]

This is called "destructuring".这被称为“解构”。

It could save you some lines of code in some cases, eg I have a,b,c as integers and want their string values as sa,sb,sc:在某些情况下,它可以为您节省一些代码行,例如,我将 a、b、c 作为整数并希望它们的字符串值为 sa、sb、sc:

sa, sb,sc = [str(e) for e in [a,b,c]]

or, even better或者,甚至更好

sa, sb,sc = map(str, (a,b,c) )

Not a good idea to do this;这样做不是一个好主意; what will you do with the variables after you define them?定义变量后,您将如何处理它们?

But supposing you have a good reason, here's how to do it in python:但是假设你有一个很好的理由,下面是如何在 python 中做到这一点:

for n, val in enumerate(ll):
    globals()["var%d"%n] = val

print var2  # etc.

Here, globals() is the local namespace presented as a dictionary.这里, globals()是作为字典呈现的本地命名空间。 Numbering starts at zero, like the array indexes, but you can tell enumerate() to start from 1 instead.编号从零开始,就像数组索引一样,但您可以告诉enumerate()从 1 开始。

But again: It's unlikely that this is actually useful to you.但同样:这不太可能对您有用。

You should go back and rethink why you "need" dynamic variables.您应该回过头来重新思考为什么“需要”动态变量。 Chances are, you can create the same functionality with looping through the list, or slicing it into chunks.很有可能,您可以通过循环遍历列表或将其切成块来创建相同的功能。

If the number of Items doesn't change you can convert the list to a string and split it to variables.如果项目的数量没有改变,您可以将列表转换为字符串并将其拆分为变量。

wedges = ["Panther", "Ali", 0, 360]
a,b,c,d = str(wedges).split()
print a,b,c,d

Instead, do this:相反,请执行以下操作:

>>> var = ['xx','yy','zz']
>>> var[0]
'xx'
>>> var[1]
'yy'
>>> var[2]
'zz'

I am assuming you are obtaining the list by way of an SQL query.我假设您通过 SQL 查询获取列表。 Why can't you commit to a length?为什么你不能承诺一个长度? With that, it seems obvious to me that you wish to take those values and execute additional SQL commands using each value from that newly acquired list separately.这样,对我来说,很明显您希望获取这些值并分别使用新获取的列表中的每个值执行其他 SQL 命令。 This is not a way off concept if you take it from an SQL perspective, and if I am correct I will provide the syntax.如果您从 SQL 的角度来看,这不是一个偏离概念的方法,如果我是正确的,我将提供语法。 However, you will not need to create separate variable names with this solution and not lose the versatility you are working toward.但是,您无需使用此解决方案创建单独的变量名称,也不会失去您正在努力实现的多功能性。

I have found a decent application for it.我找到了一个不错的应用程序。 I have a bunch of csv files which I want to save as a dataframe under their name:我有一堆 csv 文件,我想以它们的名字保存为数据框:

all_files = glob.glob(path + "/*.csv")
name_list = []
for f in all_files:
    name_list.append(f[9:-4])
for i,n in enumerate(name_list):
    globals()[n] = pd.read_csv(all_files[i])

This should do it (though using exec is not recommended):这应该可以(尽管不推荐使用 exec ):

for num in range(len(your_list)):
    exec('var'+str(num)+' = your_list[num]')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM