1

I want to sort a list so that I can feed in an attribute of the list into a loop. Let me elaborate :

Let's say I have:

data = [('turtle', 'sock'), ('frog', 'hat'), ('turtle', 'shirt'), ('frog', 'boot')]

and I only want the tuples that are related to the 'turtle', so I want:

newdata = [('turtle', 'sock'), ('turtle', 'shirt')]

Then I want to put 'sock' and 'shirt' in a list so that I can do something like:

lst = ['sock', 'shirt']

Then I can do something like

print "what is the turtle wearing?" 
for item in lst:
    print "the turtle is wearing a " + item

My idea was to sort the array so that all things related to the turtle could be put into a separate list. Then split that, but my knowledge of list is minimal. So any help or forwarding to helpful links is greatly appreciated. I hope this is a nice basic example to express my needs.

5
  • 2
    Are you sure you don't want a dict -> list mapping? Commented Jun 6, 2014 at 16:16
  • I will be presented with data in an array. If using your suggestion is easier I would love to hear how to use that instead. Commented Jun 6, 2014 at 16:18
  • sorted(list(map(operator.itemgetter(1), filter(lambda x: x[0] == 'turtle', data)))). Oh yeah, don't forget to import operator Commented Jun 6, 2014 at 16:19
  • ... but it is better to process the list once and generate a dict item -> wearing dict as @FatalError suggested. Commented Jun 6, 2014 at 16:21
  • Okay I looked them up some, I think that may work well! do you know of a good place for examples? Commented Jun 6, 2014 at 16:23

2 Answers 2

6

It's probably most appropriate to build a dict that holds what each animal wears (as I mentioned in the comment):

from collections import defaultdict

data = [('turtle', 'sock'), ('frog', 'hat'), ('turtle', 'shirt'), ('frog', 'boot')]

d = defaultdict(list)
for animal, clothing in data:
    d[animal].append(clothing)

print d['turtle']
Sign up to request clarification or add additional context in comments.

Comments

0
data = [('turtle', 'sock'), ('frog', 'hat'), ('turtle', 'shirt'), ('frog', 'boot')]

def function(key):
    listWithKey = []
    for element in data:
        if element[0] == key:
            listWithKey.append(element[1])
    return listWithKey

print(function("turtle"))

This is a more basic approach just using lists and loops. The output is ['sock', 'shirt']

1 Comment

This approach could be written more simply using list comprehensions. [x[1] for x in data if x[0] == 'turtle']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.