[Tutor] column heading

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jun 26 04:34:46 EDT 2020


On 26/06/2020 04:46, SUMAN KANTI ROY wrote:
> a=[1,2,3,4,5,6,7,8,9,10]
> arr=[[1,2],[2,23],[4,5]]
> dic={}
> for i in range(0,len(arr)):
>     if arr[i][0] not in dic:
>         dic[arr[i][0]]=arr[i][1]

Any time you see yourself writing code like this
you should give yourself a hard slap! Its virtually
never the right thing to do in Python. Even if you
need the index you can use enumerate(). But usually
you don't even need that.

In this case you can use variable unpacking to write:

for a,b in arr:
   if a not in dic:
      dic[a] = b

Which is significantly easier to read, and debug.

> arr1=[]
> def find_key(val,dic):
>     for i in dic.keys():
>         if dic[i]==val:
>             return i

Similarly here, if you use dic.items instead of
keys you can avoid indexing.

for k,v in dic.items():
    if val == v:
       return k

> new_arr=sorted(dic.values(),reverse=True)

ok...

> ans= [[0 for i in range(3)] for i in range(len(new_arr))]
> for i in range(len(new_arr)):
>     ans[i][0]=a[i]
>     ans[i][1]=find_key(new_arr[i],dic)
>     ans[i][2]=new_arr[i]

ans = ['device, 'R B N', 'CQI']
for index,item in enumerate(new_arr):
    ans.append([ a[index],   # probably a better way of doing this
                 find_key(item,dic),
                 item])

> I want to make it 3 column matrix ,,,with column heading
> name['device',R.B.N','CQI']

Try to avoid using indexes they are error prone and hard to
read or debug.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list