I am trying to determine the majority in a list of lists for a project I am working on. My problem is that the code will run in an environment that not allow me to use packages. Can someone refer me to an algorithm that does what I am asking or let me know about a way to do it with pre built functions in python that don't require outside packages?. Thank you for your time.
Example:
data = [ ["hello", 1], ["hello", 1], ["hello", 1], ["other", 32] ]
Output:
["hello", 1]
You can actually use a dictionairy to save the lists as keys and use the values as count. Then you can take the maximum count, to get your result.
data = [ ["hello", 1], ["hello", 1], ["hello", 1], ["other", 32] ]
# Make a dictionary:
dic = {}
# Loop over every item in the data
for item in data:
# Convert to tuple, since a list is unhashable:
entry = tuple(item)
# Add one to the count
# dic.get() gets the value of the entry in the dictionairy
# if this exists. Else, it sets the value to 0.
dic[entry] = dic.get(entry, 0) + 1
# Get the maximum argument by using a lambda function
# on the items in the dictionary. Get the key by taking index 0.
result = max(dic.items(), key = lambda x: x[1])[0]
You might want to convert the tuple back to a list by
result = list(result)
Try this:
data = [ ["hello", 1], ["hello", 1], ["hello", 1], ["other", 32] ]
for i in data:
if data.count(i) == max(data.count(i) for i in data):
res = i
print(res)
Or this:
res = [i for i in data if data.count(i) == max(data.count(i) for i in data)][0]
print(res)
Output:
['hello', 1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.