1

Ok, I fell into the XY trap. Sorry for that. I'll rewrite my prblem:

I have a list of numbers, eg. l = [1,3,5,1,0,0,0]

I need a string containing the number for each number > 0. Let's say the string is

string = "Your number is %s" % (x)

How can I get this to work? Especially if there is two times the same number?

~~~~~~~~~~

Old Text:

I need some help here: I have a list, for example

numbers = [1,5,3,0,0,0,0]

Now I want to define a new variable for each of the numbers that is larger than zero and assign the number to it. For example I take the list above and end up with the variables:

o = 1
p = 5
q = 3

Also, what is important, if two numbers are the same, I still need one new variable for each of them, while those variable will have the same value.

So if my list was:

numbers = [1,5,3,1,0,0,0]

I need new variables like this:

o = 1
p = 5
q = 3
r = 1

Therefore I made the following function:

def check(LIST):
    for x in LIST:
        if x > 0:
            #from here on I need help

I hope it became clear what I mean and that someone can help :)

Greetings

mrietschel
  • 11
  • 2
  • 5
    http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Ignacio Vazquez-Abrams Oct 23 '14 at 21:06
  • 1
    I suspect you don't actually need new variables for every non-zero entry. When you have some potentially huge number of things to keep track of, you want a data-structure of some sort. In this case `[x for x in LIST if x > 0]` might suit your needs. – genisage Oct 23 '14 at 21:09
  • 1
    http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html – mgilson Oct 23 '14 at 21:13
  • 2
    See also http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html for why this is stupid and what you should be doing instead. – jwodder Oct 23 '14 at 21:14

1 Answers1

1
numbers = [1,5,3,1,0,0,0]
o = ord("o")
from itertools import count
for i,val in zip(count(o),(n for n in numbers if n > 0)):
    globals()[chr(i)] = val

print o
print p

but I suspect, as mentioned in the comments, that you really dont want to do this

based on your updated question

 print "\n".join(["your number is %s"%x for x in set(y for y in numbers if y > 0)])
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179