Solved

Python list of tuples

Posted on 2008-10-15
4
762 Views
Last Modified: 2011-04-14
Hi,

I have a list of tuples and would like to create a list as described below:
Given list of tuples:
[(datetime.datetime(2008, 6, 21, 0, 0), 26, 'A'),
(datetime.datetime(2008, 6, 22, 0, 0), 22, 'B'),
(datetime.datetime(2008, 6, 22, 0, 0), 15, 'C'),
(datetime.datetime(2008, 6, 22, 0, 0), 16, 'A'),
(datetime.datetime(2008, 6, 23, 0, 0), 17, 'A'),
(datetime.datetime(2008, 6, 23, 0, 0), 0, 'B'),
(datetime.datetime(2008, 6, 23, 0, 0), 14, 'C')]

Resulted list required:
Dates=[datetime.datetime(2008, 6, 21, 0, 0),datetime.datetime(2008, 6, 22, 0, 0),datetime.datetime(2008, 6, 23, 0, 0)]
A=[26,16,17]
B=[0,22,0]
c=[0,15,14]

Here we are constructing list for DATES, A,B & C.As you can see in resulted list for A,B,C, it put 0 if there is no data for given date. I am not sure how I can achieve these resulted list for Dates,A,B,C.

Thanks,
0
Comment
Question by:punit
  • 2
4 Comments
 
LVL 15

Assisted Solution

by:mish33
mish33 earned 83 total points
ID: 22731621
Given the list is sorted by date:
from itertools import groupby
from operator import itemgetter
 
Dates = []
A = []
B = []
C = {}
for date,it in groupby(input_list, itemgetter(0)):
  Dates.append(date)
  d = dict((k,v) for d,v,k in it)
  A.append(d.get('A',0))
  B.append(d.get('B',0))
  C.append(d.get('C',0))

Open in new window

0
 
LVL 29

Expert Comment

by:pepr
ID: 22738176
mish33: The line 7 have to be changed to C = []. Nice solution; however, the input_list must be sorted by the date. It is the case in the example. It depends how it is collected.

On the other hand, it may be rather difficult to understand to a beginner.

0
 
LVL 29

Accepted Solution

by:
pepr earned 84 total points
ID: 22738263
The snippet below show similar solution without using the itertools and operator modules. It is not plain simple either (in comparison with mish33's). On the other hand, the goal itself seems to be rather complicated. The separation of the datetime (in one list, by position) from the lists for the identification where values are coupled with the date by positions...
import datetime
 
lst = [
(datetime.datetime(2008, 6, 21, 0, 0), 26, 'A'),
(datetime.datetime(2008, 6, 22, 0, 0), 22, 'B'),
(datetime.datetime(2008, 6, 22, 0, 0), 15, 'C'),
(datetime.datetime(2008, 6, 22, 0, 0), 16, 'A'),
(datetime.datetime(2008, 6, 23, 0, 0), 17, 'A'),
(datetime.datetime(2008, 6, 23, 0, 0), 0, 'B'),
(datetime.datetime(2008, 6, 23, 0, 0), 14, 'C')
]
 
dates = {}     # empty dictionary of structures related to datetimes
idset = set()  # empty set of identifications like 'A', 'B', 'C'
 
for dt, n, ident in lst:
    if dt not in dates:
        dates[dt] = {}      # empty dict of id's
    dates[dt][ident] = n    # value for the date and ident
    idset.add(ident)        # possibly new identification (globally)
 
idlst = sorted(list(idset)) # result like ['A', 'B', 'C'] 
print 'Identifications:', repr(idlst)
 
# Dates with capital = the first wanted list, dates with small
# letter is the dictionary date -> dict of (id, value).
Dates = sorted(dates.keys())
print 'Dates=' + repr(Dates)
 
# Prepare dict of id -> list of values.
result = dict((ident, []) for ident in idlst)
 
# Loop in the order of the collected dates (sorted).
for dt in Dates:
    iddic = dates[dt]   # shortcut reference to the dic of (id, value)
    for ident in idlst: # through all known id's
        result[ident].append(iddic.get(ident, 0)) # zero if value not found
 
# Display the results.
for ident in idlst: # through all known id's
    print ident + '=' + repr(result[ident])

Open in new window

0
 
LVL 2

Assisted Solution

by:exile_4
exile_4 earned 83 total points
ID: 23798306
Hi punit,

mish33 and pepr already provided you the solutions, I just came across on this Question and just wanted to show another way of achieving the same result using the combination of list comprehension, set/dict/list/sorted built-in function way.

Cheers....
import datetime
 
data = [(datetime.datetime(2008, 6, 21, 0, 0), 26, 'A'), (datetime.datetime(2008, 6, 22, 0, 0), 22, 'B'), (datetime.datetime(2008, 6, 22, 0, 0), 15, 'C'), (datetime.datetime(2008, 6, 22, 0, 0), 16, 'A'), (datetime.datetime(2008, 6, 23, 0, 0), 17, 'A'), (datetime.datetime(2008, 6, 23, 0, 0), 0, 'B'), (datetime.datetime(2008, 6, 23, 0, 0), 14, 'C')]
 
Dates = list(sorted(set([item[0] for item in data]))) # combination of list comprehension, set,list and sorted built-in function
A = []
B = []
C = []
 
for dt in Dates: #Here we loop through the filtered date
    d = dict([(item2,item1) for item0, item1, item2 in data if item0 == dt]) #again we use list comprehension and dict built-in function and extract the last 2 items beside the datetime    
    A.append(d.get('A',0))
    B.append(d.get('B',0))
    C.append(d.get('C',0))
    
print Dates
print A
print B
print C

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Python tuple index error 4 87
Python negative lookahead for aaa:bbb@hostname 6 116
How to generate square thumbnail using perl 13 86
Python On Mouseover Save URL/Link 4 71
Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question