I am trying to implement a genetic algorithm in python. I have a list of 100 objects, sorted, and I need to access the top 30 plus 20 random others. My method is:
random.shuffle(list[30:]) #keep top 30, shuffle the rest
for x in range (50):
list[x].do_stuff
This doesn't work, the list is unchanged. Is my syntax wrong or is my entire method impossible?
thanks
you probably want to do this
your_sliced_list = a[30:]
random.shuffle(your_sliced_list)
a[30:] = your_sliced_list
list is a python builtin so you shouldn't use it as a variable name as it overwrites the builtin, thats why in the code I have used a instead of list.
The reason why your code wasn't working was that when you slice the list it creates a new list which isn't assigned to a variable and random.shuffle shuffles that.
Related
I am learning lists and trying to create a list and add data to it.
mylist=[]
mylist[0]="hello"
This generates Error.
Why cant we add members to lists like this, like we do with arrays in javascript.
Since these are also dynamic and we can add as many members and of any data type to it.
In javascript this works:
var ar=[];
ar[0]=333;
Why this dosent work in Python and we only use append() to add to list.
mylist[0] = 'hello' is syntactic sugar for mylist.__setitem__(0, 'hello').
As per the docs for object.__setitem__(self, key, value):
The same exceptions should be raised for improper key values as for
the __getitem__() method.
The docs for __getitem__ states specifically what leads to IndexError:
if value outside the set of indexes for the sequence (after any
special interpretation of negative values), IndexError should be
raised.
As to the purpose behind this design decision, one can write several chapters to explain why list has been designed in this way. You should familiarise yourself with Python list indexing and slicing before making judgements on its utility.
Lists in Python are fundamentally different to arrays in languages like C. You do not create a list of a fixed size and assign elements to indexes in it. Instead you either create an empty list and append elements to it, or use a list-comprehension to generate a list from a type of expression.
In your case, you want to add to the end, so you must use the .append method:
mylist.append('hello')
#["hello"]
And an example of a list comprehension:
squares = [x**2 for x in range(10)]
#[1,4,9,16,25,36,49,64,81,100]
When I was a python beginner, I could create a multiple lines for loop that make a list of 1~100:
a=[]
for i in range(1,101):
a.append(i)
When I knew how to write a single line for loop, I could simply my code.
a=[ _ for _ in range(1,101)]
When I review python document and relearn python in detail now, I find range() built-in function it can directly make a list, but I look no one doing this. Why?
a=range(1,101)
In Python 2.x
If you want to create a list of numbers from 1 to 100, you simply do:
range(1, 101)
In Python 3.x
range() no longer returns a list, but instead returns a generator. We can easily convert that into a list though.
list(range(1, 101))
When I review python document and relearn python in detail now, I find
range() built-in function it can directly make a list, but I look no
one doing this.
Depends, if you are using Python 2.X it does but for Python 3.X it produces a range object which should be iterated upon to create a list if you need to.
But in any case for all practical purpose extending a range object as a List comprehension is useless and have an unnecessary memory hogging.
Im trying to write a function but simply cant get it right. This is supposed to be a merge function the merges as follows: the function recieves as an input a list of lists(m lists, all ints). The function creates a list that contains the indexes of the minimun values in each list of the input(each list of the list of lists, overall m indexes). example:
lst_of_lsts= [[3,4,5],[2,0,7]]
min_lst= [0,1]
At each stage, the function chooses the minimum value from that list and adds it to a new list called merged. Then, it erases it from the list of indexes(min_lst) and adds the next index which is now the new minimum.
At the end it returns merged which is an organized list from small ints to big ints. example:
merged= [0,2,3,4,5,7]
Another thing is that Im not allowed to change the original input.
def min_index(lst):
return min(range(len(lst)), key=lambda n: lst[n])
def min_lists(lstlst):
return [min_index(lst) for lst in lstlst]
then
min_lists([[3,4,5],[2,0,7]]) # => [0, 1]
Edit:
This site doesn't exist to solve your homework for you. If you work at it and your solution doesn't do what you expect, show us what you've done and we'll try to point out your mistake.
I figure my solution is OK because it's correct, but in such a way that your teacher will never believe you wrote it; however if you can understand this solution it should help you solve it yourself, and along the way teach you some Python-fu.
I am trying to find a way of creating objects based on the size of two lists. I have to create an object for each combination of indices of the two lists, i.e. if both lists is of the length 3, 9 new objects should be created and defined.
The lists can be of rather large lengths and it would make the script a lot nicer if I did not have to use an if loop to go through all possible combinations.
A first I thought I could do the following:
for i in range(len(list1)):
for j in range(len(list2):
Name_of_Object+[i]+[j] = (object definition)
But this is not possible and I get the following error:
SyntaxError: can't assign to operator
But is there a way of creating objects based on indices of a list?
Best,
Martin
(I am using the Canopy environment to do my python programming.)
Why not define these objects in a list and then you can access individual variables as li[i][j]
li = []
for i in range(len(list1)):
tempLi = []
for j in range(len(list2)):
tempLi.append((object definition))
li.append(tempLi)
we can't concatenate to an operator but we can use it an array. that is
Name_of_Object[i][j] = (object definition)
Maybe you could do your assignment with an exec statement
exec("Name_of_Object{0}{1} = object declaration".format(i,j))
But I don't think this is a good idea because you won't be able to call your objects without an exec statement further in your program unless you specificaly want Name_of_Object01 or Name_of_Object02,...
for instance if you need to loop over your instances each time you want to do something with it you will need to write:
exec("Name_of_Object{0}{1}.method(...)".format(i,j))
So I think you should you use a multidimensional array
http://diveintopython3.ep.io/native-datatypes.html
I've found that link but it seems to rely on the fact that I first have to hard create the list. How can I create a list in Python if it's empty at first. I'm coming from a C# background so this is kind of weird so far.
For example the .append() method is what I'm looking for, but it relies on the fact that the list first exists. Any suggestions?
You can create an empty list like this
L=list()
or
L=[]
As noted by others, you can create an empty list with the list literal operator [].
Its worth noting that you can initialise the list with values if you always need to start with a few values already in place:
a = 5
L = [42, -12, a]