简体   繁体   中英

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.

Assuming a1,a2,...,a10 were in an array named a you could get what you want into an array called b by doing:

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 :

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.

You can also do it within a dict comprehension :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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