How to list sets with tuple as elements, separated by the first argument of each tuple

Asked 2 years ago, Updated 2 years ago, 18 views

First of all, suppose you have the following dictionary types:

xdic={sub1:{(0,A), (1,C),(0,B),(0,B),(1,D)}, sub2:{(0,A),(2,C),(1,B),(3,D)}}

I don't know how to divide this (for each key) by the first argument of the value and put it in a list with the key name first.

In other words,

key:about sub1
Summarize 0s into arguments:(sub1,A,B)
Summarize 1 into arguments: (sub1,C,D)

key:about sub2
Summarize 0s into arguments:(sub2,A)
Summarize 1 into arguments:(sub2,B)
Summarize 2 into arguments:(sub2,C)
Summarize 3 into arguments: (sub2,D)

I'm looking for this kind of output.

The environment is python 2.7.Thank you for your understanding.

python

2022-09-30 17:45

3 Answers

This is an example of turning it in a loop.

#!/usr/bin/python2
# coding —utf-8
from__future_import print_function

xdic = {
        'sub1': {(0, 'A'), (0, 'B'), (1, 'C'), (1, 'D')},
        'sub2': {(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D')},
        }


default_per_first_item(pre, collection):
    result={}
    for vin collection:
        first_item=v[0]
        if first_item not in result:
            result [first_item] = [pre]

        # If the value tab is determined to be two elements, the following loop is not required.
        # Like result[first_item].append(v[1]).
        rest_items=v[1:]
        for i in rest_items:
            result [first_item].append(i)

    return result


for key, value index.items():
    print("about:", key)
    fork, vindic_per_first_item(key,value).items():
        print(k, ":", v)

Output:

about:sub2
0: ['sub2', 'A']
1: ['sub2', 'B']
2: ['sub2', 'C']
3: ['sub2', 'D']
about —sub1
0: ['sub1', 'B', 'A']
1: ['sub1', 'C', 'D']

I was thinking about correcting the question by editing a little bit, but I stopped because there might be discrepancies with other people's answers depending on the timing.
Here's what it is.

Dictionary values are given in the list

However, this dictionary (substituted to xdic) is surrounded by {} instead of [], so it is set (set) instead of a list.
As long as it is in accordance with this purpose, it is fine, but there may be no order, so please be careful.
As you can see from the answer output, the order is indefinite.

Summarize into a list

The results show (sub1, A, B), which is also enclosed by () instead of [], so it will not be listed and will be tabled.
(This may have been shown as a pseudocode rather than a representation of the Python value.)
I changed it to a list in my answer.

First Argument for Value

The term is used to refer to what is passed to the function (argument).
If you are referring to an element in a list or other content, you can use it as an element of a list.
It's not called the 引first argument 」, it's called the 最初first element. /

xdic={sub1:{(0,A), (1,C),(0,B),(0,B),(1,D)}, sub2:{(0,A),(2,C),(1,B),(3,D)}}

Variables such as sub1, sub2l, and A in are set to the appropriate values in the program, but if you want to indicate fragments of code, it's easy to communicate with independent code as much as possible.
In this case, I don't think all constants (string) will affect the main purpose of the question.
I chose a string in my answer.

Note:
Someone else fixed a part of it.
Please note that the above is a comment about the first version.


2022-09-30 17:45

xdic={'sub1':{(0,'A'), (1,'C'), (0,'B'), (1,'D')},
      'sub2': {(0, 'A'), (2, 'C'), (1, 'B'), (3, 'D')},}

Write simply using set and inclusion.

Python 2

for key, value index.items():     
    print'\nkey:'%(key,) for %s
    for first in { f for f, _in value }:
        print'%s: %s'% (first, [key] + [s for f, sin value if f == first ],)

Python 3

for key, value index.items():
    print('\nkey:{} for '.format(key))
    for first in { f for f, _in value }:
        print('{}:{}.format(first, [key]) + [s for f, sin value if f == first]))

Output:

key:understanding sub2
0:('sub2', 'A')
1:('sub2', 'B')
2:('sub2', 'C')
3:('sub2', 'D')

key —About sub1
0:('sub1', 'B', 'A')
1:('sub1', 'C', 'D')

A list without duplication is generated for the first element of the tuple by setting it to a set by {f for f,_in value}, and a list of second elements of the tuple corresponding to each value is generated.If the only purpose is to write with a print statement, write as above.

If you want to put it in a list, put it in a dict as follows.

result={}
for key, value index.items():
    result [key] = {}
    for first in { f for f, _in value }:
        result [key] [first] = [s for f, sin value if f == first]

Output:

{'sub1':{0:['A', 'B', 1:['D', 'C']},
 'sub2': {0:['A'], 1:['B'], 2:['C'], 3:['D']}}


2022-09-30 17:45

from print import print
from functional import seq

xdic = {'sub1': {(0, 'A'), (1, 'C'), (0, 'B'), (1, 'D')},
      'sub2': {(0, 'A'), (2, 'C'), (1, 'B'), (3, 'D')},}

print(
    seq(xdic.items())
    .sorted()
    .map(lambda(k,v):(k,seq(v)))
    .map(lambda(k,v):(v.group_by_key().map(lambdae:sorted(e[1]))),k))
    .map(lambda(v,k):v.map(lambda:[k]+e))
)
[['sub1', 'A', 'B', ['sub1', 'C', 'D']],
 [['sub2', 'A', ['sub2', 'B', ['sub2', 'C', ['sub2', 'D']]]]

The method chain is not available, so the readability is extremely poor, but it looks like this.

from print import print
from itertools import groupby

xdic = {'sub1': {(0, 'A'), (1, 'C'), (0, 'B'), (1, 'D')},
      'sub2': {(0, 'A'), (2, 'C'), (1, 'B'), (3, 'D')},}

print(map(lambda key,l):l.insert(0,key)orl,
                           sorted(
                               map(lambdax:(key,map(lambday:y[1],sorted(x[1]))),
                                   groupby(xdic[key], key=lambdax:x[0])))
                           , sorted(xdic)))

Results

[['sub1', 'A', 'B', ['sub1', 'C', 'D']],
 [['sub2', 'A', ['sub2', 'B', ['sub2', 'C', ['sub2', 'D']]]]

What's the point of writing like this?

Map-Reduce, Spark, and others use functional-style writing to deform the list.In fact, if you write in PySpark, the code will be very similar.


2022-09-30 17:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.