7
7
7j72014-04-07 06:46:24
PHP
7j7, 2014-04-07 06:46:24

Selecting and sorting an array

Good time of the day, I ask you to help in one task with which I have not been able to figure it out for more than a day, you need to extract all the same values ​​\u200b\u200bfrom the associated array and transfer them separately, adding a new element, for example, there is an array:

arr = {'a': [1,2,3], 'b': [6,7,8], 'c': [7,11,2], 'e': [45,2,10]}

need to get something like this
res = {'a': [1,3], 'b': [6,8], 'c': [11], 'e': [45,10], 'a,c,e':[2], 'b,c': [7]}

Offer options in any programming language.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey K, 2014-04-07
@7j7

Hard to read but works:

arr = {'a': [1,2,3], 'b': [6,7,8], 'c': [7,11,2], 'e': [45,2,10]}
res_arr = []
for key, value in arr.items():
    for v in value:
        for r in res_arr:
            if v in r['key']:
                r['value'].add(key)
                break
        else:
            res_arr.append({
                'key': set([v]),
                'value': set([key])
            })

res_dict = {}
for r in res_arr:
    key = ','.join(r['value'])
    if res_dict.get(key):
        res_dict[key].extend(r['key'])
    else:
        res_dict[key] = list(r['key'])

M
MrButek, 2014-04-07
@MrButek

from functools import reduce
from operator import add

def yolo(arr):
  unique = set
  def concatenate(lists):
    return reduce(add, lists)
  def keys_for(val):
    return [key for key in arr if val in arr[key]]
  def pairs():
    return [(keys_for(val), val) for val in unique(concatenate(arr.values()))]
  result = {}
  for pair in pairs():
    keys, val = ','.join(pair[0]), pair[1]
    if keys not in result:
      result[keys] = []
    result[keys].append(val)
  return result

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question