简体   繁体   中英

Python: sort a list of tuples in a specific order

I have the following list of tuples that can be ordered in a variety of ways. For example it can look like this:

data = [ ("name", "Derek Carr"),
         ("college", "Fresno State"),
         ("jersey", 4),
         ("team", "Oakland Raiders") ]

Or like this:

data = [ ("college", "Fresno State"),
         ("jersey", 4),
         ("name", "Derek Carr"),
         ("team", "Oakland Raiders") ]

The contents are the same every time but the order of the tuples are different. How can I create a new list that looks exactly like this every time:

condensed_data = ["Derek Carr", "Oakland_Raiders"]

EDIT: (1) Data list fixed. (2) The reason these lists having varying order is because they're constructed from dictionaries

I'm assuming you mean your data looks like this:

people = [
          [("name", "Derek Carr"),
           ("college", "Fresno State"),
           ("jersey", 4),
           ("team", "Oakland Raiders")],
          [("college", "Fresno State"),
           ("jersey", 4),
           ("name", "Derek Carr"),
           ("team", "Oakland Raiders")]
         ]

That is, you have a list of lists, each of which contains valid tuples (your examples were not valid Python).

First, we're going to convert each list of tuples into a dictionary mapping keys to values:

data = map(dict, people)

Now, we can extract just the information you want per person:

for p in data:
    p_data = [p["name"], p["team"]]


If you want to do this for only one person:

 data = [("name", "Derek Carr"), ("college", "Fresno State"), ("jersey", 4), ("team", "Oakland Raiders")] person_data = dict(data) result = [person_data["name"], person_data["team"]] 

Assuming you have a list of tuples:

[v for key in ["name", "team"] for k, v in data if k == key]
# ['Derek Carr', 'Oakland Raiders']

Or you can use normal loops:

lst = []
for key in ['name', 'team']:
    for k, v in data:
        if k == key:
            lst.append(v)

lst
# ['Derek Carr', 'Oakland Raiders']

Here is a good primer on how to sort in python: https://wiki.python.org/moin/HowTo/Sorting .

The condensed_data you have though does not have all the entries? If you're looking to get only the condensed data, you might want to try a list comprehension, such as:

condensed_data = sorted([item[1] for item in data if item[1] in ('Derek Carr', 'Oakland Raiders')])

You compare the first part of your tuple (or dict) with "name" and "team" and if it matches then insert the second part into your condensed_data . No need to sort anything here.

For example:

res = [None, None]

for tup in data:
    if tup[0] == 'name':
        res[0] = tup[1]
    elif tup[0] == 'team':
        res[1] = tup[1]

>>> print(res)
['Derek Carr', 'Oakland Raiders']

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