简体   繁体   中英

How can I separate and traverse data in a list of tuples in Python 2.6?

Background

Updated: Here is the horrendous list I'm working with (please excuse the list's false title). The length and data is subject to change because I'm retrieving this information from an ever-changing database.

Desired Outcome

I will further explain my purposes because I am unsure of the best way to go about this. Each number represents an ID as noted below . I need to create an XML file where Software elements have Target sub-elements based upon the SoftwareID and TargetID matching up in the tuple.

For example:

SoftwareID    TargetID                 XML Representation
----------------------------------------------------------------------
    65          115    <-- This Software element (id=65) has only one Target
                           sub-element (id=115)
    138         218    <-- This Software element (id=138) will have multiple
    138         219        Target sub-elements (ids=218, 219, 220)
    138         220 

Attempt

I've played with unpacking the sequence as done here , but the list is much too long for this implementation. I get an error that says .
I see now that this is actually a list of tuples instead of just a single tuple, so this wouldn't work anyway.

I've tried this implementation but get an error that says

As for the rest of my implementation, I am lost without being able to separate this stupid list.

Question

  • How can I separate the data from this list of tuples in order to use it for the implementation described in the Desired Outcome section?

its unclear what the actual problem is ... but maybe this will help resolve the issue

data = {}
for lhs,rhs in my_list_of_tuples:

    try:
        data[lhs].append(rhs)
    except KeyError:
        data[lhs] = [rhs]

print data.items()[:5]

to explain a little more simply lets look at it differently

my_list_of_tuples = [(1,2),(3,5),(7,8),(7,9)]
for item in my_list_of_tuples:
    #on first loop item=(1,2) ; 2nd loop item=(3,5); 3rd loop item=(7,8)
    left_number = item[0] 
    right_number = item[1]
    #these 2 lines can be simplified to
    left_number,right_number = item

    #now if left number is already in the data dictionary we will append the new right number to its list
    try:
        data[left_number].append(right_number)
    except KeyError: #: if the left_number is not already in our data dictionary
        data[left_number] = [right_number] #: create a new list that contains only the right number

#now that we are done we have data that maps left numbers to right numbers
print data
#{1:[2],3:[5],7:[8,9]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM