a = [(477, u'19'),(477, u'21'),(477, u'24'),(1511, u'20'),(1511, u'23')] def squashList(sortedList): lastElement = 0 itemsToAdd = [] dictionary = {} for i,item in enumerate(sortedList): items = str(item).split(',') index = int(str(items[0]).replace("(","")) value = int(str(items[1]).replace("u'","").replace("')","")) #first loop through if i == 0: lastElement = index; itemsToAdd.append(value); #if same as previous element, add to list elif lastElement == index: itemsToAdd.append(value); #if different that last element, add list to dictionary, create new list, add value and track new element elif lastElement != index: length = len(itemsToAdd); dictionary[lastElement] = itemsToAdd[0:length]; del itemsToAdd[0:length]; itemsToAdd.append(value); lastElement = index; if i == len(sortedList)-1: dictionary[index] = itemsToAdd[0:len(itemsToAdd)]; return dictionary squashedList = squashList(a) print(str(squashedList[477]).strip('[]').replace(' ',''))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question