excercise python list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: excercise python list (/thread-8227.html) |
excercise python list - Kykoss - Feb-10-2018 Hi,I want you to help me with the solution of an exercise which is very difficult for me to simply tell me the solution in a very simple and understandable way and then try in a difficult way. the exercise is the following:::://Make a list of 20 places and fill them in red, green, blue in random order and then put them in the right order (based on this order :: red, green, blue); RE: excercise python list - j.crater - Feb-10-2018 Hello, we are not solving assignments for people here. Post your attempt - code in Python code tags and potential errors in error tags. It will also help to show the result/output you get and the result you want to have. From there we can help you correct the mistakes in code and guide you in the right direction. RE: excercise python list - Kykoss - Feb-10-2018 my codec is: import random list=[] colors=['red','green','blue'] for i in range(20): list.append(random.choice(colors)) print (list) for i in range(20): if list[i]=="blue": list.insert(19,list.pop(i)) if list[i]=="red": list.insert(0,list.pop(i)) print (list)I would like to ask whether it is done in a simpler and easier way without many commands (for,if,while,)a simple way. RE: excercise python list - nilamo - Feb-10-2018 You can skip the whole second for loop if you just sort it: list.sort(reverse=True) RE: excercise python list - Kykoss - Feb-10-2018 with the function sort you can send me this solution based on the variable sort RE: excercise python list - nilamo - Feb-10-2018 It's built into the list type. There's nothing to send.>>> help([].sort) Help on built-in function sort: sort(...) method of builtins.list instance L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* RE: excercise python list - Kykoss - Feb-11-2018 the right way but not the one I'm looking at can we do it with the command if i in.....I want to sort the colors in the order I gave some commands you wrote I do not know them yet (if,in,while,for,def) RE: excercise python list - DeaD_EyE - Feb-11-2018 Please can you try to make full sentence. English is not my mother language and currently I don't understand your question. Do you want to have the order of appending? Then do nothing, task is finished. The order stays in a list. If you need to sort the items in the list by name (A-Za-z), just use the in-place sort of list. list1 = ['s', 'z', 'd', 'a'] list1.sort() print(list1)If you need the original list and a sorted list: list1 = ['s', 'z', 'd', 'a'] list2 = sorted(list1) print(list2)If you need a custom order, you have to write your own key-function for sorted. You can read here more: https://wiki.python.org/moin/HowTo/Sorting |