python - Create new variables inside a loop, that were not previously defined -


For example, in this loop:

  lst = [1,2,3 , 4,5,6,7,8,9] First of all: print i  

Instead of printing me just once, once every time a new variable for me assays Is there a way to do it? So that I get something: item1 = 1 item2 = 2 item3 = 3 and so on.

Or is there no way that you should know how much I will need?

For example, the user returns a variable for each item in the list lst, or any other list (with any other lane).

The issue of doing what you are thinking for all is capable of making variable calls later. My code searches for segments within a list that is fit for a seratine criterion, and I want to be able to reach the segment later, or at least I'm new to programming So, if you have a better way, please tell me.

You want to split the data according to a specific criteria. Suppose you have a function figure_out_class which gives you a description for the class that you fall on the data, then you can use a dictionary to do this: i / lst For key = figure_out_class (i) i: for

  partitions = {} if the key partitions are not in: partition [key] = [] partition [key] .append (i)  

Is this "what's already the key?" You can already avoid using those sections that you know you need, or default default from the collection using the defaultdict :

  = Import for the default dict (list) I for an example, say that you want to classify numbers like  weird  I  

or Even :

  def figure_out_class (number): return ("strange" if the number% 2 and "even")  

Applying that function to the previous part of the code will give you:

  gt; & Gt; & Gt; Division ['weird'] [1, 3, 5, 7, 9] & gt; & Gt; & Gt; Partition ['To date'] [2, 4, 6, 8]  

Comments