Naveen C.
Naveen C.

Reputation: 3345

PYTHON how to make as many variables as needed

I have a loop that's reading over a text file. Each time the loop finds something different, I want it to make a new variable and assign the value in that line of text to the newly created variable. So if the text file looks like this:

3 3 6 1 3 6

The program would've made 3 variables, one for 1, one for 3, and one for 6. How can I do this>

Upvotes: 0

Views: 342

Answers (6)

Paolo
Paolo

Reputation: 21056

This code should do what you have asked for.

import sys 
from string import ascii_letters 

# Task 1, remove duplicate elements. 
def nodup(fn): 
    f = open(fn) 
    data = f.read().split() 

    res = [] 
    res.extend((i for i in data if i not in res)) 
    return res 

# Task 2, create the new variables on the fly 
module = sys.modules[__name__] 
filename = "data" 
for idx, value in enumerate(nodup(filename)): 
    setattr(module, ascii_letters[idx], value) 

print (a, b, c) 
# ('3', '6', '1')

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61513

You can use the exec builtin to create variables.

Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [3,3,6,1,3,6]
>>> for e in a:
...     exec 'var%s = %e' % (e,e)
...
...
>>> var3
3.0
>>> var6
6.0
>>> var1
1.0
>>>

EDIT This is a bad solution and should never be used. It is, however, important to know that something like this IS possible.

Upvotes: 2

Eli Stevens
Eli Stevens

Reputation: 1447

There are a couple approaches:

mydict = {}
for x in myfile.read().split():
    mydict[x] = None
print mydict

Or:

class VarContainer(object):
    pass
v = VarContainer()
for x in myfile.read().split():
    setattr(v, 'var' + x, None)
print v.var3

But what you're trying to do is a bit unclear.

Upvotes: 1

Joseph Salisbury
Joseph Salisbury

Reputation: 2177

Assuming text_file is some iterable,

def get_unique_numbers(text_file):
   temp = []
   for number in text_file:
      if number not in temp:
         temp.append(number)
   return temp

Upvotes: 0

Moshe
Moshe

Reputation: 9839

You can store the values in an array:

(Assuming python 2.7) http://docs.python.org/library/array.html

You can then use array.index(x) to search if that value is already in the array, and array.append(x) to add it to the array

Upvotes: 0

pyroscope
pyroscope

Reputation: 4158

What you likely want is this...

>>> set("3 3 6 1 3 6".split())
set(['1', '3', '6'])

Upvotes: 3

Related Questions