How to print list items in python - python

I have written the following code:
def count():
a = 1
b = 5
c = 2
d = 8
i = 0
list1 = [a, b, c, d]
le = len(list1)
while (i < le):
x = max(list1)
print(x)
list1.remove(x)
i = i + 1
What I want to do is to print the largest number with its variable name like:
d:8
b:5
c:2
but using the above code I can only print the ascending list of numbers, not the corresponding variable names. Please suggest a way to fix this.

Use a dict instead:
In [2]: dic=dict(a=1, b=5, c=2, d=8)
In [3]: dic
Out[3]: {'a': 1, 'b': 5, 'c': 2, 'd': 8}
In [5]: sortedKeys=sorted(dic, key=dic.get, reverse=True)
In [6]: sortedKeys
Out[6]: ['d', 'b', 'c', 'a']
In [7]: for i in sortedKeys:
...: print i, dic[i]
...:
d 8
b 5
c 2
a 1

I think you can use OrderedDict()
from collections import OrderedDict
a, b, c, d = 1, 2, 3, 6
vars = {
'a' : a,
'b' : b,
'c' : c,
'd' : d
}
d_sorted_by_value = OrderedDict(sorted(vars.items(), key=x.get, reverse=True))
for k, v in d_sorted_by_value.items():
print "{}: {}".format(k,v)
List don't save variable names

Related

python: get percentage from collection counter

I have two lists like the following:
l1= ['a','b','c','a','b','c','c','c']
l2= ['f','g','f','f','f','g','f','f']
I have tried to get the counts of elements in the first list based on a condition:
from collections import Counter
Counter([a for a, b in zip(l1, l2) if b == 'f'])
the output is:
Counter({'a': 2, 'c': 3, 'b': 1})
instead of counts, I would like to get their percentage like the following
'a': 1, 'c': 0.5, 'b': 0.75
I have tried adding Counter(100/([a for a,b in zip(l1,l2) if b=='f'])), but I get an error.
You can try this:
from collections import Counter
l1= ['a','b','c','a','b','c','c','c']
l2= ['f','g','f','f','f','g','f','f']
d=dict(Counter([a for a,b in zip(l1,l2) if b=='f']))
k={i:j/100 for i,j in d.items()}
print(k)
To calculate percentage:
k={i:(j/l1.count(i)) for i,j in d.items()}
print(k)
Do you specifically need it to be done in one line ? If not, maybe this could work:
from collections import Counter
l1= ['a','b','c','a','b','c','c','c']
l2= ['f','g','f','f','f','g','f','f']
alpha = Counter([a for a,b in zip(l1,l2) if b=='f'])
for key, item in alpha.items():
alpha[key] = int(item)/100
print(alpha)
Calculate the frequency of characters in l1 and perform division to get percentage.
In your code b percentage should be 0.5 and not 0.75
l1 = ['a','b','c','a','b','c','c','c']
l2 = ['f','g','f','f','f','g','f','f']
from collections import Counter
a = Counter(l1)
c = Counter([a for a, b in zip(l1, l2) if b == 'f'])
c = {i:(v/a[i]) for i,v in c.items()}
print(c)
{'a': 1.0, 'c': 0.75, 'b': 0.50}

Create an adjacency matrix using a dictionary with letter values converted to numbers in python

So I have a dictionary with letter values and keys and I want to generate an adjacency matrix using digits (0 or 1). But I don't know how to do that.
Here is my dictionary:
g = { "a" : ["c","e","b"],
"b" : ["f","a"]}
And I want an output like this :
import numpy as np
new_dic = {'a':[0,1,1,0,1,0],'b':(1,0,0,0,0,1)}
rows_names = ['a','b'] # I use a list because dictionaries don't memorize the positions
adj_matrix = np.array([new_dic[i] for i in rows_names])
print(adj_matrix)
Output :
[[0 1 1 0 1 0]
[1 0 0 0 0 1]]
So it's an adjacency matrix: column/row 1 represent A, column/row 2 represent B ...
Thank you !
I don't know if it helps but here is how I convert all letters to numbers using ascii :
for key, value in g.items():
nums = [str(ord(x) - 96) for x in value if x.lower() >= 'a' and x.lower() <= 'z']
g[key] = nums
print(g)
Output :
{'a': ['3', '5', '2'], 'b': ['6', '1']}
So a == 1 b == 2 ...
So my problem is: If a take the keys a with the first value "e", how should I do so that the e is found in the column 5 line 1 and not in the column 2 line 1 ? and replacing the e to 1
Using comprehensions:
g = {'a': ['c', 'e', 'b'], 'b': ['f', 'a']}
vals = 'a b c d e f'.split() # Column values
new_dic = {k: [1 if x in v else 0 for x in vals] for k, v in g.items()}

I have three arrays of different sizes that I'm trying to print into a table

a = [1, 2, 3]
b = [a, b, c, d]
c = ["why", "cant", "i", "make", "this", "work"]
Desired output:
a b c
1 a why
2 b cant
3 c I
d make
this
work
you can reference this code.
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
c = ["why", "cant", "i", "make", "this", "work"]
def get_safenode(l, i):
if i<len(l):
an=l[i]
else:
an=''
return str(an)
maxlen = max(len(a), len(b), len(c))
print('%3s %3s %-5s' % ('a','b','c'))
for i in range(maxlen):
an = get_safenode(a, i)
bn = get_safenode(b, i)
cn = get_safenode(c, i)
print('%3s %3s %-5s'%(an, bn, cn))
The output is this.
a b c
1 a why
2 b cant
3 c i
d make
this
work

Compare 4 numbers to find if 3 are the same

I have the following Python list:
mylist = [a, b, c, d]
where a,b,c,d are integers.
I want to compare the 4 numbers and see if 3 of them are the same.
I have tried converting the list to a set, but it didn't help me.
Try collections.Counter.
import collections
x = [1, 2, 1, 1]
counter = collections.Counter(x)
if 3 in counter.values():
print('3 are the same')
Output:
3 are the same
UPDATE
If you are interested in checking for 3 or more occurrences, you can check the maximum value in the Counter like this:
if max(counter.values()) >= 3:
print('3 or more are the same')
This method has the added advantage that it works for larger lists as well without modification.
if mylist.count(mylist[0])>=3 or mylist.count(mylist[1])>=3:
print('3 are the same')
I would suggest using collections.Counter.
Convert the list to a counter. The counter should have two keys, and one of its values should be 3:
In [1]: from collections import Counter
In [2]: c = Counter([0, 1, 1, 1])
In [3]: len(c) == 2
Out[3]: True
In [4]: 3 in c.values()
Out[4]: True
In short:
In [5]: len(c) == 2 and 3 in c.values()
Out[5]: True
Let's try a example that doesn't meet the criteria:
In [8]: d = Counter([0, 0, 1, 1])
In [9]: len(d) == 2 and 3 in d.values()
Out[9]: False
Check the highest count?
max(map(mylist.count, mylist)) >= 3
This solution uses a collections.Counter
from collections import Counter
mylist1 = [1, 2, 4, 4]
mylist2 = [1, 3, 3, 3]
c1 = Counter(mylist1)
c2 = Counter(mylist2)
c1.most_common(1)
>>> [(4, 2)]
c1.most_common(1)[0][1] == 3
>>> False
c2.most_common(1)[0][1] == 3
>>> True
Here's one way:
mylist = [a, b, c, d]
d = {}
for i in mylist:
d[i] = d.get(i, 0) + 1
if 3 in d.values():
print("three are the same")
You can try this:
mylist = [a, b, c, d]
counter = {a:mylist.count(a) for a in mylist}
if 1 in counter.values() and len(counter) == 2:
print("three are the same")
You can use a collections.Counter:
from collections import Counter
same3 = Counter(mylist).most_common(1)[0][1] >= 3
This will be true if at least 3 elements are the same.

Empty a variable without destroying it

I have this piece of code:
a = "aa"
b = 1
c = { "b":2 }
d = [3,"c"]
e = (4,5)
letters = [a, b, c, d, e]
And I want to do something with it, which will empty them. Without losing their type.
Something like this:
>>EmptyVars(letters)
['',0,{},[],()]
Any hint?
Do this:
def EmptyVar(lst):
return [type(i)() for i in lst]
type() produces the type object for each value, which when called produces an 'empty' new value.
Demo:
>>> a = "aa"
>>> b = 1
>>> c = { "b":2 }
>>> d = [3,"c"]
>>> e = (4,5)
>>> letters = [a, b, c, d, e]
>>> def EmptyVar(lst):
... return [type(i)() for i in lst]
...
>>> EmptyVar(letters)
['', 0, {}, [], ()]
Similar way, just type(i)() replaced by i.__class__():
a = "aa"
b = 1
c = {"b": 2}
d = [3, "c"]
e = (4, 5)
letters = [a, b, c, d, e]
def empty_var(lst):
return [i.__class__() for i in lst]
print(empty_var(letters))
['', 0, {}, [], ()]
We can do this with the help of type() function which is generally used to display the type of any object or variable in python.
Here is the solution :
a = "aa"
b = 1
c = {"b" : 2}
d = [3, "c"]
e = (4,5)
letters = [a,b,c,d,e]
print([type(i)() for i in letters])

Categories

Resources