1

Say I have an array such as this:

namesscore = ["Rory: 1", "Rory: 4", "Liam: 5", "Liam: 6", "Erin: 8", "Liam: 2",]

and I wanted to sort that array to make it like this:

namescore = ["Rory: 1, 4", "Liam: 5, 6, 2", "Erin: 8"]

How would I do that?

2
  • It seems like you want a dictionary using the name as a key and assign them a list value that you can use append on. Commented Oct 10, 2015 at 17:11
  • By what criteria is the final array being sorted? Commented Oct 10, 2015 at 17:14

4 Answers 4

1

I'd iterate the list, and for each item split it between the name and a score. Then I'd create a dict (more accurately: an OrderedDict, to preserve the order) and accumulate the scores for each name. When the iteration is done, it can be converted to a list of strings in the desired format:

from collections import OrderedDict

def group_scores(namesscore):
    mapped = OrderedDict()
    for elem in namesscore:
        name, score = elem.split(': ')
        if name not in mapped:
            mapped[name] = []
        mapped[name].append(score)

    return ['%s%s%s' % (key, ': ', ', '.join(value)) for \
              key, value in mapped.items()]
Sign up to request clarification or add additional context in comments.

2 Comments

This returns "AttributeError: 'OrderedDict' object has no attribute 'iteritems'"
@Liwa didn't notice the python3 tag, mea culpa. I edited and replaced the iteritems() call with items(), which should work on both python 2 and 3.
0
namesscore = ["Rory: 1", "Rory: 4", "Liam: 5", "Liam: 6", "Erin: 8", "Liam: 2"]
namesscore = [tuple(el.split()) for el in namesscore]
temp = dict((el[1], el[0]) for el in namesscore)

merge = {}
for key, value in temp.iteritems():
    if value not in merge:
        merge[value] = [key]
    else:
        merge[value].append(key)

print [' '.join((k, ' '.join(v))) for k, v in merge.iteritems()]

>>> ['Rory: 1 4', 'Liam: 2 5 6', 'Erin: 8']

Comments

0
from collections import defaultdict
import operator

namesscore = ["Rory: 1", "Rory: 4", "Liam: 5", "Liam: 6", "Erin: 8", "Liam: 2",]

# Build a dictionary where the key is the name and the value is a list of scores
scores = defaultdict(list)
for ns in namesscore:
    name, score = ns.split(':')
    scores[name].append(score)

# Sort each persons scores
scores = {n: sorted(s) for n, s in scores.items()}   

# Sort people by their scores returning a list of tuples
scores = sorted(scores.items(), key=operator.itemgetter(1))   

# Output the final strings
scores = ['{}: {}'.format(n, ', '.join(s)) for n, s in scores]

print scores

> ['Rory:  1,  4', 'Liam:  2,  5,  6', 'Erin:  8']

2 Comments

This returns "["L_K: {'4'}", "L_K: {'2'}", "L_K: {'0'}", "L_K: {'1'}", "Rory_Follin: {'2'}", "Rory_Follin: {'2'}", "Rory_Follin: {'10'}"]" when run through my prgram
@Liwa Can you post your initial namesscore list? It appears your values and maybe the structure are different from your example.
0
namesscore = ["Rory: 1", "Rory: 4", "Liam: 5", "Liam: 6", "Erin: 8", "Liam: 2",]

od = {}

[ od.setdefault(a,[]).append(b) for a,b in map(lambda x : (x[0:x.find(':')],x[-1]), namesscore)]

namesscore = ['  '.join((k,' '.join(sorted(v))))  for k, v in od.items()]

print(namesscore)

['Erin  8', 'Liam  2 5 6', 'Rory  1 4']

Comments

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.