def shufflemode():
import random
combined = zip(question, answer)
random.shuffle(combined)
question[:], answer[:] = zip(*combined)
but then i get the error:
TypeError: object of type 'zip' has no len()
What do I do im so confused
I wonder the same thing. According to:
randomizing two lists and maintaining order in python
You should be able to do it like the OP tried, but i also get the same error. I think the ones from the link are using python 2 and not 3, could this be the problem?
This is an issue between Python 2 and Python 3. In Python 2 using shuffle after zip works, because zip returns a list. In Python 3: "TypeError: object of type 'zip' has no len()" because zip returns an iterator in Python 3.
Solution, use list() to convert to a list:
combined = list(zip(question, answer))
random.shuffle(combined)
The error appeared with shuffle() because shuffle() uses len().
References issue:
The zip() function in python 3
Stumbled upon this and was surprised to learn about the random.shuffle method. So I tried your example, and it worked for me in Python 2.7.5:
def shufflemode():
import random
combined = zip(question, answer)
random.shuffle(combined)
question[:], answer[:] = zip(*combined)
question = ["q1","q2","q3","q4","q5"]
answer = ["a1","a2","a3","a4","a5"]
if __name__ == "__main__":
shufflemode()
print question,answer
The result is two lists with the same randomized sequence of questions and answers*strong text*:
>>>
['q3', 'q2', 'q5', 'q4', 'q1'] ['a3', 'a2', 'a5', 'a4', 'a1']
>>>
Related
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
for i in range(1, 27):
for j in range(1,27):
if j!=i:
lst = a
print(lst)
print(a)
lst.remove(i)
lst.remove(j)
print(lst)
print(a)
List 'a' is getting smaller coz i change list 'lst', wtf is this?
I just started to perform codewars kata.
By default, python creates a reference for an object. If you want to make an actual copy with new memory what you can do is:
from copy import deepcopy
lis_copy = deepcopy(lis)
I've seen similar questions and answers on SO, but i'm struggling to understand how to apply it.
I am trying to port the following Python 2x code to Python 3x:
deals = sorted([DealData(deal) for deal in deals],
lambda f1, f2: f1.json_data['time'] > f2.json_data['time]
I've seen suggestions to use the cmp_to_key function, but i can't get it working. What am I missing?
This is my attempt with CMP_to_key:
deals = sorted(DealData, key=functools.cmp_to_key(cmp=compare_timestamps))
def compare_timestamps(x,y):
return x.json_data['timeStamp'] > y.json_data['timeStamp']
I receive the following error: cmp_to_key() missing required argument 'mycmp'(pos1)
For sorted in python 3 you need to tell it what key in the object to use for sorting
deals = sorted(
[DealData(deal) for deal in deals],
key=lambda deal_data: deal_data.json_data["time"]
)
cmp_to_key is only needed if you had an existing comparison function ie:
from functools import cmp_to_key
def compare_deals(d1, d2):
if d1.json_data["time"] > d2.json_data["time"]:
return 1
if d1.json_data["time"] < d2.json_data["time"]:
return -1
# equal
return 0
deal = sorted(
[DealData(deal) for deal in deals],
key=cmp_to_key(compare_deals)
)
The Sorting How To in the python documentation gives more examples.
I am an extremely begginer learning python to tackle some biology problems, and I came across lists and its various methods. Basically, when I am running print to my variable I get None as return.
Example, trying to print a sorted list assigned to a variable
list1=[1,3,4,2]
sorted=list1.sort()
print(sorted)
I receive None as return. Shouldn't this provide me with [1,2,3,4]
However, when printing the original list variable (list1), it gives me the sorted list fine.
Because the sort() method will always return None. What you should do is:
list1=[1,3,4,2]
list1.sort()
print(list1)
Or
list1=[1,3,4,2]
list2 = sorted(list1)
print(list2)
You can sort lists in two ways. Using list.sort() and this will sort list, or new_list = sorted(list) and this will return a sorted list new_list and list will not be modified.
So, you can do this:
list1=[1,3,4,2]
sorted=sorted(list1)
print(sorted)
Or you can so this:
list1=[1,3,4,2]
list1.sort()
print(list1)
I had a perfectly functioning sort by value in python 2.7 but I'm trying to upgrade to python 3.6 and I get that error:
TypeError: '<' not supported between instances of 'dict' and 'dict'
Here is my code
server_list = []
for server in res["aggregations"]["hostname"]["buckets"]:
temp_obj = []
temp_obj.append({"name":server.key})
temp_obj.append({"stat": server["last_log"]["hits"]["hits"][0]["_source"][system].stat})
server_list.append(temp_obj)
server_list.sort(key=lambda x: x[0], reverse=False)
Why it's considered as a dict when I declare my server_list as a list. How can I make it sort by my name attribute?
Python 2's dictionary sort order was quite involved and poorly understood. It only happened to work because Python 2 tried to make everything orderable.
For your specific case, with {'name': ...} dictionaries with a single key, the ordering was determined by the value for that single key.
In Python 3, where dictionaries are no longer orderable (together with many other types), just use that value as the sorting key:
server_list.sort(key=lambda x: x[0]['name'], reverse=False)
I am a Python 2.7 user who recently switched to python3. While reading integers separated by a blackspace/endline I used nex = iter(map(int,stdin.read().split())).next, where nex() acts as a function to input integers (Suppose for inputting an integral value in x -> x=nex(). But in python3 this doesn't seem to work. Someone please propose a workaround for using the same in Python3.
.next() method is called .__next__() in Python 3. You could use next() function to write single-source Python 2/3 compatible code:
from functools import partial
nex = partial(next, iter(iterable))
print(nex())