How do I replace a value in a matrix which corresponding to another matrix?












1















For example



a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]


And I want to get a matrix c:



c = [0.5, 0.8, 0, 0.11, 0, 0]


That's like if the i in a = ww for ww,ee in n for n in b, then replace with ee else 0



I try some if and else command and here is my code



for n in b:
for t,y in n:
for tt in a:
mmm = [y if t == ''.join(tt) else ''.join(tt)]
print(mmm)


But it failed. How should I code for this situation?










share|improve this question




















  • 3





    Shouldn't the last value in c be 0.23 ?

    – Austin
    Nov 18 '18 at 17:49











  • [dict(sum(b,)).get(int(i),0) for i in a]

    – Onyambu
    Nov 18 '18 at 21:48


















1















For example



a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]


And I want to get a matrix c:



c = [0.5, 0.8, 0, 0.11, 0, 0]


That's like if the i in a = ww for ww,ee in n for n in b, then replace with ee else 0



I try some if and else command and here is my code



for n in b:
for t,y in n:
for tt in a:
mmm = [y if t == ''.join(tt) else ''.join(tt)]
print(mmm)


But it failed. How should I code for this situation?










share|improve this question




















  • 3





    Shouldn't the last value in c be 0.23 ?

    – Austin
    Nov 18 '18 at 17:49











  • [dict(sum(b,)).get(int(i),0) for i in a]

    – Onyambu
    Nov 18 '18 at 21:48
















1












1








1








For example



a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]


And I want to get a matrix c:



c = [0.5, 0.8, 0, 0.11, 0, 0]


That's like if the i in a = ww for ww,ee in n for n in b, then replace with ee else 0



I try some if and else command and here is my code



for n in b:
for t,y in n:
for tt in a:
mmm = [y if t == ''.join(tt) else ''.join(tt)]
print(mmm)


But it failed. How should I code for this situation?










share|improve this question
















For example



a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]


And I want to get a matrix c:



c = [0.5, 0.8, 0, 0.11, 0, 0]


That's like if the i in a = ww for ww,ee in n for n in b, then replace with ee else 0



I try some if and else command and here is my code



for n in b:
for t,y in n:
for tt in a:
mmm = [y if t == ''.join(tt) else ''.join(tt)]
print(mmm)


But it failed. How should I code for this situation?







python python-3.x numpy if-statement replace






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 17:55









Austin

10.2k3828




10.2k3828










asked Nov 18 '18 at 17:37









wayne64001wayne64001

475




475








  • 3





    Shouldn't the last value in c be 0.23 ?

    – Austin
    Nov 18 '18 at 17:49











  • [dict(sum(b,)).get(int(i),0) for i in a]

    – Onyambu
    Nov 18 '18 at 21:48
















  • 3





    Shouldn't the last value in c be 0.23 ?

    – Austin
    Nov 18 '18 at 17:49











  • [dict(sum(b,)).get(int(i),0) for i in a]

    – Onyambu
    Nov 18 '18 at 21:48










3




3





Shouldn't the last value in c be 0.23 ?

– Austin
Nov 18 '18 at 17:49





Shouldn't the last value in c be 0.23 ?

– Austin
Nov 18 '18 at 17:49













[dict(sum(b,)).get(int(i),0) for i in a]

– Onyambu
Nov 18 '18 at 21:48







[dict(sum(b,)).get(int(i),0) for i in a]

– Onyambu
Nov 18 '18 at 21:48














3 Answers
3






active

oldest

votes


















1















chain + dict + list comprehension



Your b mapping is a list of lists, you can flatten this into an iterable of tuples via chain.from_iterable. Then feed to dict to create an efficient mapping.



Finally, use a list comprehension with dict.get for the desired result. Just remember to convert the values of a from str to int.



from itertools import chain

a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

b_dict = dict(chain.from_iterable(b))
c = [b_dict.get(i, 0) for i in map(int, a)]

print(c)

[0.5, 0.8, 0, 0.11, 0, 0.23]





share|improve this answer































    0














    This iterates through list a comparing it's value with first value of tuples in b list. This appends the second value of tuple to output list if the first value of tuple matches with the value in a:



    from itertools import chain

    a = ['1', '2', '3', '4', '5', '6']
    b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

    b = list(chain.from_iterable(b))
    lst =
    for x in a:
    for y, z in b:
    if y == int(x):
    lst.append(z)
    break
    else:
    lst.append(0)

    print(lst)
    # [0.5, 0.8, 0, 0.11, 0, 0.23]





    share|improve this answer

































      0














      You can convert your double-list of mappings into a lookup dictionary and use a list-comp:



      a = ['1', '2', '3', '4', '5', '6']
      b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

      # convert b to a dictionary:
      d = {str(k):v for tup in b for k,v in tup} # stringify the lookup key value
      print(d)

      # apply the lookup to a's values
      result = [d.get(k,0) for k in a]
      print(result)


      Output:



      # the lookup-dictionary
      {'1': 0.5, '2': 0.8, '4': 0.11, '6': 0.23}

      # result of list c,omprehension
      [0.5, 0.8, 0, 0.11, 0, 0.23]


      Related:




      • dict.get(key[, default])

      • Why dict.get(key) instead of dict[key]?






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53363713%2fhow-do-i-replace-a-value-in-a-matrix-which-corresponding-to-another-matrix%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1















        chain + dict + list comprehension



        Your b mapping is a list of lists, you can flatten this into an iterable of tuples via chain.from_iterable. Then feed to dict to create an efficient mapping.



        Finally, use a list comprehension with dict.get for the desired result. Just remember to convert the values of a from str to int.



        from itertools import chain

        a = ['1', '2', '3', '4', '5', '6']
        b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

        b_dict = dict(chain.from_iterable(b))
        c = [b_dict.get(i, 0) for i in map(int, a)]

        print(c)

        [0.5, 0.8, 0, 0.11, 0, 0.23]





        share|improve this answer




























          1















          chain + dict + list comprehension



          Your b mapping is a list of lists, you can flatten this into an iterable of tuples via chain.from_iterable. Then feed to dict to create an efficient mapping.



          Finally, use a list comprehension with dict.get for the desired result. Just remember to convert the values of a from str to int.



          from itertools import chain

          a = ['1', '2', '3', '4', '5', '6']
          b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

          b_dict = dict(chain.from_iterable(b))
          c = [b_dict.get(i, 0) for i in map(int, a)]

          print(c)

          [0.5, 0.8, 0, 0.11, 0, 0.23]





          share|improve this answer


























            1












            1








            1








            chain + dict + list comprehension



            Your b mapping is a list of lists, you can flatten this into an iterable of tuples via chain.from_iterable. Then feed to dict to create an efficient mapping.



            Finally, use a list comprehension with dict.get for the desired result. Just remember to convert the values of a from str to int.



            from itertools import chain

            a = ['1', '2', '3', '4', '5', '6']
            b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

            b_dict = dict(chain.from_iterable(b))
            c = [b_dict.get(i, 0) for i in map(int, a)]

            print(c)

            [0.5, 0.8, 0, 0.11, 0, 0.23]





            share|improve this answer














            chain + dict + list comprehension



            Your b mapping is a list of lists, you can flatten this into an iterable of tuples via chain.from_iterable. Then feed to dict to create an efficient mapping.



            Finally, use a list comprehension with dict.get for the desired result. Just remember to convert the values of a from str to int.



            from itertools import chain

            a = ['1', '2', '3', '4', '5', '6']
            b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

            b_dict = dict(chain.from_iterable(b))
            c = [b_dict.get(i, 0) for i in map(int, a)]

            print(c)

            [0.5, 0.8, 0, 0.11, 0, 0.23]






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 18 '18 at 18:16









            jppjpp

            100k2161111




            100k2161111

























                0














                This iterates through list a comparing it's value with first value of tuples in b list. This appends the second value of tuple to output list if the first value of tuple matches with the value in a:



                from itertools import chain

                a = ['1', '2', '3', '4', '5', '6']
                b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                b = list(chain.from_iterable(b))
                lst =
                for x in a:
                for y, z in b:
                if y == int(x):
                lst.append(z)
                break
                else:
                lst.append(0)

                print(lst)
                # [0.5, 0.8, 0, 0.11, 0, 0.23]





                share|improve this answer






























                  0














                  This iterates through list a comparing it's value with first value of tuples in b list. This appends the second value of tuple to output list if the first value of tuple matches with the value in a:



                  from itertools import chain

                  a = ['1', '2', '3', '4', '5', '6']
                  b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                  b = list(chain.from_iterable(b))
                  lst =
                  for x in a:
                  for y, z in b:
                  if y == int(x):
                  lst.append(z)
                  break
                  else:
                  lst.append(0)

                  print(lst)
                  # [0.5, 0.8, 0, 0.11, 0, 0.23]





                  share|improve this answer




























                    0












                    0








                    0







                    This iterates through list a comparing it's value with first value of tuples in b list. This appends the second value of tuple to output list if the first value of tuple matches with the value in a:



                    from itertools import chain

                    a = ['1', '2', '3', '4', '5', '6']
                    b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                    b = list(chain.from_iterable(b))
                    lst =
                    for x in a:
                    for y, z in b:
                    if y == int(x):
                    lst.append(z)
                    break
                    else:
                    lst.append(0)

                    print(lst)
                    # [0.5, 0.8, 0, 0.11, 0, 0.23]





                    share|improve this answer















                    This iterates through list a comparing it's value with first value of tuples in b list. This appends the second value of tuple to output list if the first value of tuple matches with the value in a:



                    from itertools import chain

                    a = ['1', '2', '3', '4', '5', '6']
                    b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                    b = list(chain.from_iterable(b))
                    lst =
                    for x in a:
                    for y, z in b:
                    if y == int(x):
                    lst.append(z)
                    break
                    else:
                    lst.append(0)

                    print(lst)
                    # [0.5, 0.8, 0, 0.11, 0, 0.23]






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 18 '18 at 18:01

























                    answered Nov 18 '18 at 17:51









                    AustinAustin

                    10.2k3828




                    10.2k3828























                        0














                        You can convert your double-list of mappings into a lookup dictionary and use a list-comp:



                        a = ['1', '2', '3', '4', '5', '6']
                        b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                        # convert b to a dictionary:
                        d = {str(k):v for tup in b for k,v in tup} # stringify the lookup key value
                        print(d)

                        # apply the lookup to a's values
                        result = [d.get(k,0) for k in a]
                        print(result)


                        Output:



                        # the lookup-dictionary
                        {'1': 0.5, '2': 0.8, '4': 0.11, '6': 0.23}

                        # result of list c,omprehension
                        [0.5, 0.8, 0, 0.11, 0, 0.23]


                        Related:




                        • dict.get(key[, default])

                        • Why dict.get(key) instead of dict[key]?






                        share|improve this answer




























                          0














                          You can convert your double-list of mappings into a lookup dictionary and use a list-comp:



                          a = ['1', '2', '3', '4', '5', '6']
                          b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                          # convert b to a dictionary:
                          d = {str(k):v for tup in b for k,v in tup} # stringify the lookup key value
                          print(d)

                          # apply the lookup to a's values
                          result = [d.get(k,0) for k in a]
                          print(result)


                          Output:



                          # the lookup-dictionary
                          {'1': 0.5, '2': 0.8, '4': 0.11, '6': 0.23}

                          # result of list c,omprehension
                          [0.5, 0.8, 0, 0.11, 0, 0.23]


                          Related:




                          • dict.get(key[, default])

                          • Why dict.get(key) instead of dict[key]?






                          share|improve this answer


























                            0












                            0








                            0







                            You can convert your double-list of mappings into a lookup dictionary and use a list-comp:



                            a = ['1', '2', '3', '4', '5', '6']
                            b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                            # convert b to a dictionary:
                            d = {str(k):v for tup in b for k,v in tup} # stringify the lookup key value
                            print(d)

                            # apply the lookup to a's values
                            result = [d.get(k,0) for k in a]
                            print(result)


                            Output:



                            # the lookup-dictionary
                            {'1': 0.5, '2': 0.8, '4': 0.11, '6': 0.23}

                            # result of list c,omprehension
                            [0.5, 0.8, 0, 0.11, 0, 0.23]


                            Related:




                            • dict.get(key[, default])

                            • Why dict.get(key) instead of dict[key]?






                            share|improve this answer













                            You can convert your double-list of mappings into a lookup dictionary and use a list-comp:



                            a = ['1', '2', '3', '4', '5', '6']
                            b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

                            # convert b to a dictionary:
                            d = {str(k):v for tup in b for k,v in tup} # stringify the lookup key value
                            print(d)

                            # apply the lookup to a's values
                            result = [d.get(k,0) for k in a]
                            print(result)


                            Output:



                            # the lookup-dictionary
                            {'1': 0.5, '2': 0.8, '4': 0.11, '6': 0.23}

                            # result of list c,omprehension
                            [0.5, 0.8, 0, 0.11, 0, 0.23]


                            Related:




                            • dict.get(key[, default])

                            • Why dict.get(key) instead of dict[key]?







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 18 '18 at 18:16









                            Patrick ArtnerPatrick Artner

                            23.6k62443




                            23.6k62443






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53363713%2fhow-do-i-replace-a-value-in-a-matrix-which-corresponding-to-another-matrix%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Tangent Lines Diagram Along Smooth Curve

                                Yusuf al-Mu'taman ibn Hud

                                Zucchini