-2
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])

How can I assign above values if it's needed to assign more than (let's say) 100 values or so?

KevinOelen
  • 679
  • 2
  • 10
  • 23
  • 6
    Please don't do whatever you're trying to do. Can you show the *actual* problem you're trying to solve? I assure you that a list is probably what you want instead of 100 independently named variables. – Cory Kramer Jun 30 '15 at 12:51
  • Not like that. That would be terrible to have to read. – kylieCatt Jun 30 '15 at 12:53
  • @CoryKramer Suppose I have csv file that has 100 string rows inside. What I'm trying to do is to select 50 of them randomly and assign it to 50 variables. – KevinOelen Jun 30 '15 at 12:58
  • 3
    @KevinOelen Again I ask, why 50 variables instead of a single list with 50 elements? – Cory Kramer Jun 30 '15 at 12:59

3 Answers3

4

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]
CrazyCasta
  • 24,620
  • 4
  • 41
  • 67
1

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'] 
Mazdak
  • 100,514
  • 17
  • 155
  • 179
1

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]