How to compare two outputs of data in Python - python

I created 5 rooms with same Game id and print result (list if Rooms' id). i get Game with Id and print result (list of Rooms' id. I need to check if this two outputs (rooms id are matches).
for i in range(5):
post_req = requests.post(custom_url) # create 5 custom rooms with same Game id
json_data = post_req.text
python_data = json.loads(json_data)
for i in range(len(python_data["data"])):
first_list = python_data["data"][i]["id"]
print (first_list)
# Get Rooms with Game id. It should give a list of all rooms id created with same game id
custom_get_objects = requests.get(custom_url)
json_data = custom_get_objects.text
python_get_data = json.loads(json_data)
for i in range(len(python_get_data["data"])):
second_list = python_get_data["data"][i]["id"]
print (second_list)
How to program next following logic?
if first_list.data == second_list.data:
return True
my list.data output:
2b88a706-0ae0-4cac-84b3-8f69657ac8cd
402210ca-8397-4329-9c96-770f1d93ab43
78c9faae-74ad-44f8-9bab-b54bb8815afb
9a374566-d992-40a8-9e23-9cfe83ced532
f39794ed-d2f1-4443-a3f3-ef12534387d6
i tried to sort and iterated one list in another, but output is not what i expected. If you know or have any idea, please let me know.

If the order in your lists does not matter you can use sorted(listA) == sorted(listB) to compare them. If the order matters then simply use listA == listB.
Example:
aList = [2, 4, 5]
bList = [2, 5, 4]
print(aList == bList)
print(sorted(aList) == sorted(bList))
Output:
False
True

Related

Find max value of a column based on another in python

i have 2d list implementation as follows. It shows no. of times every student topped in exams:-
list = main_record
['student1',1]
['student2',1]
['student2',2]
['student1',5]
['student3',3]
i have another list of unique students as follows:-
list = students_enrolled
['student1','student2','student3']
which i want to display student ranking based on their distinctions as follows:-
list = student_ranking
['student1','student3','student2']
What built in functions can be useful. I could not pose proper query on net. In other words i need python equivalent of following queries:-
select max(main_record[1]) where name = student1 >>> result = 5
select max(main_record[1]) where name = student2 >>> result = 2
select max(main_record[1]) where name = student3 >>> result = 3
You define a dict base key of studentX and save the max value for each student key then sort the students_enrolled base max value of each key.
from collections import defaultdict
main_record = [['student1',1], ['student2',1], ['student2',2], ['student1',5], ['student3',3]]
students_enrolled = ['student1','student2','student3']
# defind dict with negative infinity and update with max in each iteration
tmp_dct = defaultdict(lambda: float('-inf'))
for lst in main_record:
k, v = lst
tmp_dct[k] = max(tmp_dct[k], v)
print(tmp_dct)
students_enrolled.sort(key = lambda x: tmp_dct[x], reverse=True)
print(students_enrolled)
Output:
# tmp_dct =>
defaultdict(<function <lambda> at 0x7fd81044b1f0>,
{'student1': 5, 'student2': 2, 'student3': 3})
# students_enrolled after sorting
['student1', 'student3', 'student2']
If it is a 2D list it should look like this: l = [["student1", 2], ["student2", 3], ["student3", 4]]. To get the highest numeric value from the 2nd column you can use a loop like this:
numbers = []
for student in list:
numbers.append(student[1])
for num in numbers:
n = numbers.copy()
n.sort()
n.reverse()
student_index = numbers.index(n[0])
print(list[student_index], n[0])
numbers.remove(n[0])

How to get a unique value from a list in python

Imagine I have this list:
list = ['a','a','b','a']
I would like to do something like this:
print(unique(list))
to retrieve the unique item(s), so python will output b. How could I do this?
Count the items, keep only those which have a count of 1:
>>> data = ['a','a','b','a']
>>> from collections import Counter
>>> [k for k,v in Counter(data).items() if v == 1]
['b']
Using set() property of Python, we can easily check for the unique values. Insert the values of the list in a set. Set only stores a value once even if it is inserted more then once. After inserting all the values in the set by list_set=set(list1), convert this set to a list to print it.
for more ways check : https://www.geeksforgeeks.org/python-get-unique-values-list/#:~:text=Using%20set()%20property%20of,a%20list%20to%20print%20it.
Example to make a unique function :
# Python program to check if two
# to get unique values from list
# using set
# function to get unique values
def unique(list1):
# insert the list to the set
list_set = set(list1)
# convert the set to the list
unique_list = (list(list_set))
for x in unique_list:
print x,
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)
output should be:
the unique values from 1st list is
40 10 20 30
the unique values from 2nd list is
1 2 3 4 5
You can also use numpy.unique example:
`
#Ppython program to check if two
# to get unique values from list
# using numpy.unique
import numpy as np
# function to get unique values
def unique(list1):
x = np.array(list1)
print(np.unique(x))
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)
`
output should be :
the unique values from 1st list is
[10 20 30 40]
the unique values from 2nd list is
[1 2 3 4 5]
Fore more please check "https://www.geeksforgeeks.org/python-get-unique-values-list/#:~:text=Using%20set()%20property%20of,a%20list%20to%20print%20it."
You could use collections.Counter() for this, e.g.:
from collections import Counter
my_list = ['a','a','b','a']
counts = Counter(my_list)
for element, count in counts.items():
if count == 1:
print(element)
would print b and nothing else in this case.
Or, if you'd like to store the result in a list:
from collections import Counter
my_list = ['a','a','b','a']
counts = Counter(my_list)
unique_elements = [element for element, count in counts.items() if count == 1]
unique_elements is ['b'] in this case.
Count the appearance of an element in the list, and store it in a dictionary
From the dictionary, check which elements has only one appearance
Store the unique (one appearance) elements in a list
Print the list
You can try this:
my_list = ['a','a','b','a']
my_dict = {}
only_one = []
#Step 1
for element in my_list:
if element not in my_dict:
my_dict[element] = 1
else:
my_dict[element] += 1
#Step 2 and Step 3
for key, value in my_dict.items():
if value == 1:
only_one.append(key)
#Step 4
for unique in only_one:
print(unique)
Output:
b
In case you are wondering what other variables contain:
my_dict = {'a': 3, 'b': 1}
only_one = ['b']
Most straight forward way, use a dict of counters.
a = ['a','a','b','a']
counts = {}
for element in a:
counts[element] = counts.get(element, 0) + 1
for element in a:
if counts[element] == 1:
print(element)
out:
b

How do you check whether a list contains a dictionary inside?

I have a code which checks to see whether a column contains a list and if found it will explode that list and convert the exploded column into int if it is numeric. However, I ran into a problem as some lists in my file contains dictionaries. How would I include that into my existing code to check whether the list contains a dictionary/keys, and if so, it should not explode that column and leave it as it is.
Current Code:
x = (doc.applymap(type) == list).all()
y = x.index[x].tolist()
for i in y:
doc= doc.explode(i)
if (doc[i].str.isnumeric().all()) == True:
x = (doc[i].to_frame().columns)
doc[x] = doc[x].fillna(0).astype(int)
Input:
ID
"number": [1,2,3,4],
"number": [{"enabled": 1,2,3,4}]
Expected Output
ID
1
2
3
4
[{"enabled": 1,2,3,4}]
Might not be the best way but this does the job:
for i in y:
m = str(doc[i][0]).strip('[]')
if m[0] == '{' and m[-1] == '}':
pass
else:
doc = doc.explode(i)
if (doc[i].str.isnumeric().all()) == True:
x = (doc[i].to_frame().columns)
doc[x] = doc[x].fillna(0).astype(int)
I'm not completely sure what you are trying to do but this is how you can check if a dict is in a list.
The upper one only returns True or False if the list contains a dict, the second one gives you the item itself.
mylist = [1, 2, 3,{"key":"value"} 4, 5]
if any(type(x) is dict for x in mylist):
#List contains a dict
else:
#do other stuff
for x in mylist:
item_type = type(x)
if(item_type is dict):
#item is dict
else:
#item is not dict

Differentiate output based on people names?

I'm working on this code that basically gives output based on the input (the users names) that the user give, i need help/ advice on how i can differentiate the output given based on the name.
i've tried if statements, but its really basic detecting, since i've only studied python not so long ago.
# var
import random
nopes = ("nope1", "nope2", "nope3")
list1 = 1
list2 = 2
list3 = 3
list4 = 4
list5 = 5
list6 = 6
list7 = 7
list8 = 8
list9 = 9
# functions
def mainfunc():
if a in "name1":
print(list1)
elif a in "name2":
print(list2)
elif a in "name3":
print(list3)
elif a in "name4":
print(list4)
elif a in "name5":
print(list5)
elif a in "name6":
print(list6)
elif a in "name7":
print(list7)
elif a in "name8":
print(list8)
elif a in "name9":
print(list9)
else:
talk()
def talk():
print(random.choice(nopes))
#syntax's
a = input("What's your name? : ")
mainfunc()
yes, it works. but with a single typo the code would not work as i expected, and im trying to avoid that.
I don't completely get the intention of your code, but if you want to print differnt lists based on the input, you could use a dictionary instead of the several list#-objects.
lists = {
"name1": ["a","b","c"],
"name2": ["d","e","f"]
}
a = "name1"
if (a in lists.keys()):
print(lists[a])
# Output: ['a', 'b', 'c']
That way, you just have to maintain the dictionary object and not many single objects and the elseifs

python dictionary - list of lists to dict

I'm trying to take list of lists and convert in to dictionary. See code below
yearend = [['empl','rating1','rating2','rating3'],['mike','4','4','5'],
['sam','3','2','5'],['doug','5','5','5']]
extract the employee names
employee = [item[0] for item in yearend] #select 1st item from each list
employee.pop(0) # pop out the empl
print(employee)
### output##################################################
##['mike', 'sam', 'doug']###################################
###Output###################################################
###extract the various rating types
yearend1 = yearend [:] # make a copy
rating = yearend1.pop(0) # Pop out the 1st list
rating.pop(0)
print(rating)
### output##################################################
##['rating1', 'rating2', 'rating3']#########################
###Output###################################################
# pick employee and rating and convert rating to numeric
empl_rating = {t[0]:t[1:] for t in yearend1}
for key,value in empl_rating.items():
value = list(map(int, value))
empl_rating[key] = value
print(empl_rating)
### output##################################################
##{'mike': [4, 4, 5], 'sam': [3, 2, 5], 'doug': [5, 5, 5]}##
###Output###################################################
I extracted the data like above and now Iam trying to put together in to dict (New_dicts) so that when
New_dicts['sam']['rating1']
I get 3 or
New_dicts['doug']['rating3']
I get 5. What I'm struggling is how to put this data together?
def todict(ratings) :
a ={}
a["rating1"] = ratings [0]
a["rating2"] = ratings [1]
a["rating3"] = ratings [2]
return a
One way to solve your problem is to get rid of the first row with the headings then just do:
{item[0] : todict(item[1:])
for item in your_list}
BTW this sol is based of off how you wanted to index it. I'm sure there is a more generic sol out there.
Because what you want is essentially just a nested dict
You can use a dict comprehension:
New_dicts = {line[0]: {yearend[0][i + 1]: int(rating) for i, rating in enumerate(line[1:])} for line in yearend[1:]}

Categories