list - compare file line by line python -


what elegant way go through sorted list it's first index? input:

meni22   xxxx xxxx meni32_2 xxxx xxxx meni32_2 xxxx xxxx meni45_1 xxxx xxxx meni45_1 xxxx xxxx meni45   xxxx xxxx 

is go trough line line:

list1 = [] list2 = [] line in input:     if line[0] not in list1:     list.append(line) else:     list2.append(line) 

example won't work. adds first match of line[0] , continues. rather have go through list, add list1 lines finds once , rest list2.

after script:

list1:  meni22   xxxx xxxx meni45   xxxx xxxx  list2:   meni45_1 xxxx xxxx meni45_1 xxxx xxxx meni32_2 xxxx xxxx meni32_2 xxxx xxxx 

you can use collections.counter:

from collections import counter lis1 = [] lis2 = [] open("abc") f:     c = counter(line.split()[0] line in f)  key,val in c.items():     if val == 1:         lis1.append(key)     else:         lis2.extend([key]*val) print lis1 print lis2 

output:

['meni45', 'meni22'] ['meni32_2', 'meni32_2', 'meni45_1', 'meni45_1'] 

edit:

from collections import defaultdict lis1 = [] lis2 = []  open("abc") f:     dic = defaultdict(list)     line in f:         spl =line.split()         dic[spl[0]].append(spl[1:])  key,val in dic.items():     if len(val) == 1:         lis1.append(key)     else:         lis2.append(key) print lis1 print lis2  print dic["meni32_2"]  #access columns related key the dict 

output:

['meni45', 'meni22'] ['meni32_2', 'meni45_1'] [['xxxx', 'xxxx'], ['xxxx', 'xxxx']] 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -