简体   繁体   English

Python:一次分配多个变量

[英]Python: assigning multiple variables at once

a,b,c,d,e,f,g,h,i,j = ''.join(doc[a1]),''.join(doc[a2]),''.join(doc[a3]),''.join(doc[a4]),''.join(doc[a5]),''.join(doc[a6]),''.join(doc[a7]),''.join(doc[a8]),''.join(doc[a9]),''.join(doc[a10])

如果需要分配超过(假设)100 个左右的值,我该如何分配上述值?

Your code is a bit confusing.你的代码有点混乱。 It would be more clear to do:这样做会更清楚:

a = ''.join(doc[a1])
b = ''.join(doc[a2])
c = ''.join(doc[a3])
d = ''.join(doc[a4])
e = ''.join(doc[a5])
f = ''.join(doc[a6])
g = ''.join(doc[a7])
h = ''.join(doc[a8])
i = ''.join(doc[a9])
j = ''.join(doc[a10])

The syntax you're using is usually used in instances like:您使用的语法通常用于以下情况:

str_ = "a,b"
a, b = str_.split(",")
# a = "a", b = "b"

What you want sounds like it could be handled by an array, but you'll have to turn a1,a2,...,a10 into an array.您想要的听起来像是可以由数组处理,但是您必须将 a1,a2,...,a10 转换为数组。

Assuming a1,a2,...,a10 were in an array named a you could get what you want into an array called b by doing:假设 a1,a2,...,a10 在名为a的数组中,您可以通过执行以下操作将所需内容放入名为 b 的数组中:

b = [''.join(doc(a_part)) for a_part in a]

In that case you can use assignment, the pythonic way is using a dictionary.if doc is a dictionary you can loop over its values and use enumerate to create a dictionary :在这种情况下,您可以使用赋值,pythonic 的方式是使用字典。如果doc是字典,您可以遍历其值并使用enumerate创建字典:

d={}
for i,j in enumerate(doc.values()):
  d['a{}'.format(i)]=''.join(j)

If doc is not a dictionary and is another type of iterable objects you can just loop over itself.如果doc不是字典而是另一种类型的可迭代对象,您可以循环遍历自身。

You can also do it within a dict comprehension :您也可以在 dict 理解中执行此操作:

d={'a{}'.format(i):''.join(j) for i,j in enumerate(doc.values())}

And then you can simply access to your variables with indexing :然后你可以简单地使用索引访问你的变量:

print d['a1'] # or d['an'] 

That is a very unreadable way to do that.这是一种非常难以理解的方式来做到这一点。 Plus, you're trying to do something manually that you should be trying to do programmatically.另外,您正在尝试手动执行一些您应该尝试以编程方式执行的操作。 Loops and lists are your friend.循环和列表是您的朋友。 You don't want to have to keep track of that many variables.您不想必须跟踪这么多变量。 Rather it is more convenient to keep track of items in a list.相反,跟踪列表中的项目更方便。 You'd be better served with something like this:像这样的东西会更好地为您服务:

new_list = []
for key in doc:
    new_list.append(''.join(doc[key]))

which can be written more succinctly as可以更简洁地写成

new_list = [''.join(doc[key]) for key in doc]

or if doc is a list:或者如果 doc 是一个列表:

new_list = [''.join(item) for item in doc]

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

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