Running a single for loop with previously created numbered variablesGetting the name of a variable as a stringHow do I create a variable number of variables?Peak detection in a 2D arrayWhat is the purpose of the single underscore “_” variable in Python?Python: take the content of a list and append it to another list“Large data” work flows using pandasconverting a number of lists into single dictWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?Python: Generate string variables based on number with the same value as the numbervariable number of dependent nested loopsSquare a number to the power of an array element-wise using python loop

Can I rely on this github repository files?

Can somebody explain Brexit in a few child-proof sentences?

Could the E-bike drivetrain wear down till needing replacement after 400 km?

Varistor? Purpose and principle

Find last 3 digits of this monster number

Engineer refusing to file/disclose patents

How much character growth crosses the line into breaking the character

How do I repair my stair bannister?

Query about absorption line spectra

Do Legal Documents Require Signing In Standard Pen Colors?

Has Darkwing Duck ever met Scrooge McDuck?

Generating adjacency matrices from isomorphic graphs

Global amount of publications over time

Reply 'no position' while the job posting is still there

What does this horizontal bar at the first measure mean?

Indicating multiple different modes of speech (fantasy language or telepathy)

In Star Trek IV, why did the Bounty go back to a time when whales were already rare?

Have I saved too much for retirement so far?

My friend sent me a screenshot of a transaction hash, but when I search for it I find divergent data. What happened?

If a character with the Alert feat rolls a crit fail on their Perception check, are they surprised?

Should I install hardwood flooring or cabinets first?

What is this type of notehead called?

Can I sign legal documents with a smiley face?

Why in book's example is used 言葉(ことば) instead of 言語(げんご)?



Running a single for loop with previously created numbered variables


Getting the name of a variable as a stringHow do I create a variable number of variables?Peak detection in a 2D arrayWhat is the purpose of the single underscore “_” variable in Python?Python: take the content of a list and append it to another list“Large data” work flows using pandasconverting a number of lists into single dictWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?Python: Generate string variables based on number with the same value as the numbervariable number of dependent nested loopsSquare a number to the power of an array element-wise using python loop













0















I'm working on analyzing a .h5ad file, which has the file type AnnData.



I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ...)



Now, I would like to take the mean of all the separate rows in each list. Of course this could be easily done by making many loops, but I thought it would be interesting to try and do it in in a single loop.



The code to do this for a single list is as follows:



means1 = []
for q in range(0, len(x1.var)):
means1.append(np.mean(x1.X[:, q2])


Now, I would like to be able to substitute means1 and x1 with variable numbers.
For means1 this can be solved by making it a dict and using a second for with range(0, number) as follows:



x = 
for q1 in range(0, 20):
for q2 in range(0, len(x1.var)):
x['mean' + q1] = np.mean(x1.X[:,q2])


But because the variable that I use in x1 already exists, it is impossible to just use string formatting like 'x' + q1, since a str doesn't have the attribute .X.



Is there any way to do this, or should I accept that it's impossible?










share|improve this question
























  • What is the data type of your variables x1, x2...?

    – Ralf
    Mar 7 at 9:24











  • Better to not create separate lists in the first place, use a single nested list or dict.

    – Daniel Roseman
    Mar 7 at 9:35















0















I'm working on analyzing a .h5ad file, which has the file type AnnData.



I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ...)



Now, I would like to take the mean of all the separate rows in each list. Of course this could be easily done by making many loops, but I thought it would be interesting to try and do it in in a single loop.



The code to do this for a single list is as follows:



means1 = []
for q in range(0, len(x1.var)):
means1.append(np.mean(x1.X[:, q2])


Now, I would like to be able to substitute means1 and x1 with variable numbers.
For means1 this can be solved by making it a dict and using a second for with range(0, number) as follows:



x = 
for q1 in range(0, 20):
for q2 in range(0, len(x1.var)):
x['mean' + q1] = np.mean(x1.X[:,q2])


But because the variable that I use in x1 already exists, it is impossible to just use string formatting like 'x' + q1, since a str doesn't have the attribute .X.



Is there any way to do this, or should I accept that it's impossible?










share|improve this question
























  • What is the data type of your variables x1, x2...?

    – Ralf
    Mar 7 at 9:24











  • Better to not create separate lists in the first place, use a single nested list or dict.

    – Daniel Roseman
    Mar 7 at 9:35













0












0








0








I'm working on analyzing a .h5ad file, which has the file type AnnData.



I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ...)



Now, I would like to take the mean of all the separate rows in each list. Of course this could be easily done by making many loops, but I thought it would be interesting to try and do it in in a single loop.



The code to do this for a single list is as follows:



means1 = []
for q in range(0, len(x1.var)):
means1.append(np.mean(x1.X[:, q2])


Now, I would like to be able to substitute means1 and x1 with variable numbers.
For means1 this can be solved by making it a dict and using a second for with range(0, number) as follows:



x = 
for q1 in range(0, 20):
for q2 in range(0, len(x1.var)):
x['mean' + q1] = np.mean(x1.X[:,q2])


But because the variable that I use in x1 already exists, it is impossible to just use string formatting like 'x' + q1, since a str doesn't have the attribute .X.



Is there any way to do this, or should I accept that it's impossible?










share|improve this question
















I'm working on analyzing a .h5ad file, which has the file type AnnData.



I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ...)



Now, I would like to take the mean of all the separate rows in each list. Of course this could be easily done by making many loops, but I thought it would be interesting to try and do it in in a single loop.



The code to do this for a single list is as follows:



means1 = []
for q in range(0, len(x1.var)):
means1.append(np.mean(x1.X[:, q2])


Now, I would like to be able to substitute means1 and x1 with variable numbers.
For means1 this can be solved by making it a dict and using a second for with range(0, number) as follows:



x = 
for q1 in range(0, 20):
for q2 in range(0, len(x1.var)):
x['mean' + q1] = np.mean(x1.X[:,q2])


But because the variable that I use in x1 already exists, it is impossible to just use string formatting like 'x' + q1, since a str doesn't have the attribute .X.



Is there any way to do this, or should I accept that it's impossible?







python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 9:26









Ralf

6,86841437




6,86841437










asked Mar 7 at 9:19









HarryMuesliHarryMuesli

203




203












  • What is the data type of your variables x1, x2...?

    – Ralf
    Mar 7 at 9:24











  • Better to not create separate lists in the first place, use a single nested list or dict.

    – Daniel Roseman
    Mar 7 at 9:35

















  • What is the data type of your variables x1, x2...?

    – Ralf
    Mar 7 at 9:24











  • Better to not create separate lists in the first place, use a single nested list or dict.

    – Daniel Roseman
    Mar 7 at 9:35
















What is the data type of your variables x1, x2...?

– Ralf
Mar 7 at 9:24





What is the data type of your variables x1, x2...?

– Ralf
Mar 7 at 9:24













Better to not create separate lists in the first place, use a single nested list or dict.

– Daniel Roseman
Mar 7 at 9:35





Better to not create separate lists in the first place, use a single nested list or dict.

– Daniel Roseman
Mar 7 at 9:35












3 Answers
3






active

oldest

votes


















1














First idea: you could iterate over all of your lists in an outer loop and apply your second idea to that. Then create a subdict for every list inside x. With this, you would have 3 Loops for everything instead of one for every single list:



x = 
list_number = 1
for list in x1, x2, x3, x4:
for q1 in range(0, 20):
for q2 in range(0, len(list.var)):
x['x'.format(list_number)]['mean' + str(q1)] = np.mean(list.X[:,q2])
list_number += 1


We could also substitute one for loop with a dict comprehension (which does not really take a loop away, but shortens the code):



x['x'.format(list_number)] = 'mean'+str(q1): np.mean(list.X[:,q2]) for q2 in range(0, len(list.var))


That being said, while i don't know exactly how your data is structured, having a dict of the form



lists = 'x1': [the_list], 'x2': [other_list], ...



is always better for this type of task. Since there is no really good way to get the name of a variable, having them stored in a dict as string keys makes it way easier to work with them. This enables you to do something like this:



means = name: 'mean'+ str(q + 1): np.mean(lists[name].X[:,q]) for q in range(len(lists[name].var)) for name in lists


which will return a dictionary of the form



means = 'x1': 'mean1': mean_1, 'mean2': mean_2, ..., 'x2': 'mean1': mean_1,......


Doing all of this with a single loop is impossible, at least with how your data is structured right now, because you have to iterate over at least two iterables:



  1. all the lists;


  2. all elements of each lists variables.






share|improve this answer
































    2















    I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ..)




    Most often when you find yourself using such a naming scheme, you really want a list or dict instead.






    share|improve this answer






























      0














      A simple solution would be to build a list with all the x variables and then iterate over it.



      Maybe something like this:



      x_list = [x1, x2, x3, x4]
      means =

      for i, x in enumerate(x_list):
      for j in range(len(x.var)):
      key = (i, j)
      means[key] = np.mean(x.X[:, j])


      Does this work for you?






      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%2f55040116%2frunning-a-single-for-loop-with-previously-created-numbered-variables%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














        First idea: you could iterate over all of your lists in an outer loop and apply your second idea to that. Then create a subdict for every list inside x. With this, you would have 3 Loops for everything instead of one for every single list:



        x = 
        list_number = 1
        for list in x1, x2, x3, x4:
        for q1 in range(0, 20):
        for q2 in range(0, len(list.var)):
        x['x'.format(list_number)]['mean' + str(q1)] = np.mean(list.X[:,q2])
        list_number += 1


        We could also substitute one for loop with a dict comprehension (which does not really take a loop away, but shortens the code):



        x['x'.format(list_number)] = 'mean'+str(q1): np.mean(list.X[:,q2]) for q2 in range(0, len(list.var))


        That being said, while i don't know exactly how your data is structured, having a dict of the form



        lists = 'x1': [the_list], 'x2': [other_list], ...



        is always better for this type of task. Since there is no really good way to get the name of a variable, having them stored in a dict as string keys makes it way easier to work with them. This enables you to do something like this:



        means = name: 'mean'+ str(q + 1): np.mean(lists[name].X[:,q]) for q in range(len(lists[name].var)) for name in lists


        which will return a dictionary of the form



        means = 'x1': 'mean1': mean_1, 'mean2': mean_2, ..., 'x2': 'mean1': mean_1,......


        Doing all of this with a single loop is impossible, at least with how your data is structured right now, because you have to iterate over at least two iterables:



        1. all the lists;


        2. all elements of each lists variables.






        share|improve this answer





























          1














          First idea: you could iterate over all of your lists in an outer loop and apply your second idea to that. Then create a subdict for every list inside x. With this, you would have 3 Loops for everything instead of one for every single list:



          x = 
          list_number = 1
          for list in x1, x2, x3, x4:
          for q1 in range(0, 20):
          for q2 in range(0, len(list.var)):
          x['x'.format(list_number)]['mean' + str(q1)] = np.mean(list.X[:,q2])
          list_number += 1


          We could also substitute one for loop with a dict comprehension (which does not really take a loop away, but shortens the code):



          x['x'.format(list_number)] = 'mean'+str(q1): np.mean(list.X[:,q2]) for q2 in range(0, len(list.var))


          That being said, while i don't know exactly how your data is structured, having a dict of the form



          lists = 'x1': [the_list], 'x2': [other_list], ...



          is always better for this type of task. Since there is no really good way to get the name of a variable, having them stored in a dict as string keys makes it way easier to work with them. This enables you to do something like this:



          means = name: 'mean'+ str(q + 1): np.mean(lists[name].X[:,q]) for q in range(len(lists[name].var)) for name in lists


          which will return a dictionary of the form



          means = 'x1': 'mean1': mean_1, 'mean2': mean_2, ..., 'x2': 'mean1': mean_1,......


          Doing all of this with a single loop is impossible, at least with how your data is structured right now, because you have to iterate over at least two iterables:



          1. all the lists;


          2. all elements of each lists variables.






          share|improve this answer



























            1












            1








            1







            First idea: you could iterate over all of your lists in an outer loop and apply your second idea to that. Then create a subdict for every list inside x. With this, you would have 3 Loops for everything instead of one for every single list:



            x = 
            list_number = 1
            for list in x1, x2, x3, x4:
            for q1 in range(0, 20):
            for q2 in range(0, len(list.var)):
            x['x'.format(list_number)]['mean' + str(q1)] = np.mean(list.X[:,q2])
            list_number += 1


            We could also substitute one for loop with a dict comprehension (which does not really take a loop away, but shortens the code):



            x['x'.format(list_number)] = 'mean'+str(q1): np.mean(list.X[:,q2]) for q2 in range(0, len(list.var))


            That being said, while i don't know exactly how your data is structured, having a dict of the form



            lists = 'x1': [the_list], 'x2': [other_list], ...



            is always better for this type of task. Since there is no really good way to get the name of a variable, having them stored in a dict as string keys makes it way easier to work with them. This enables you to do something like this:



            means = name: 'mean'+ str(q + 1): np.mean(lists[name].X[:,q]) for q in range(len(lists[name].var)) for name in lists


            which will return a dictionary of the form



            means = 'x1': 'mean1': mean_1, 'mean2': mean_2, ..., 'x2': 'mean1': mean_1,......


            Doing all of this with a single loop is impossible, at least with how your data is structured right now, because you have to iterate over at least two iterables:



            1. all the lists;


            2. all elements of each lists variables.






            share|improve this answer















            First idea: you could iterate over all of your lists in an outer loop and apply your second idea to that. Then create a subdict for every list inside x. With this, you would have 3 Loops for everything instead of one for every single list:



            x = 
            list_number = 1
            for list in x1, x2, x3, x4:
            for q1 in range(0, 20):
            for q2 in range(0, len(list.var)):
            x['x'.format(list_number)]['mean' + str(q1)] = np.mean(list.X[:,q2])
            list_number += 1


            We could also substitute one for loop with a dict comprehension (which does not really take a loop away, but shortens the code):



            x['x'.format(list_number)] = 'mean'+str(q1): np.mean(list.X[:,q2]) for q2 in range(0, len(list.var))


            That being said, while i don't know exactly how your data is structured, having a dict of the form



            lists = 'x1': [the_list], 'x2': [other_list], ...



            is always better for this type of task. Since there is no really good way to get the name of a variable, having them stored in a dict as string keys makes it way easier to work with them. This enables you to do something like this:



            means = name: 'mean'+ str(q + 1): np.mean(lists[name].X[:,q]) for q in range(len(lists[name].var)) for name in lists


            which will return a dictionary of the form



            means = 'x1': 'mean1': mean_1, 'mean2': mean_2, ..., 'x2': 'mean1': mean_1,......


            Doing all of this with a single loop is impossible, at least with how your data is structured right now, because you have to iterate over at least two iterables:



            1. all the lists;


            2. all elements of each lists variables.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 7 at 10:18

























            answered Mar 7 at 10:12









            FlobFlob

            711110




            711110























                2















                I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ..)




                Most often when you find yourself using such a naming scheme, you really want a list or dict instead.






                share|improve this answer



























                  2















                  I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ..)




                  Most often when you find yourself using such a naming scheme, you really want a list or dict instead.






                  share|improve this answer

























                    2












                    2








                    2








                    I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ..)




                    Most often when you find yourself using such a naming scheme, you really want a list or dict instead.






                    share|improve this answer














                    I've created separate lists based on some clustering program, and named the lists according to their cluster number (i.e. x1, x2, x3, x4 ..)




                    Most often when you find yourself using such a naming scheme, you really want a list or dict instead.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 7 at 9:35









                    bruno desthuilliersbruno desthuilliers

                    51.7k54465




                    51.7k54465





















                        0














                        A simple solution would be to build a list with all the x variables and then iterate over it.



                        Maybe something like this:



                        x_list = [x1, x2, x3, x4]
                        means =

                        for i, x in enumerate(x_list):
                        for j in range(len(x.var)):
                        key = (i, j)
                        means[key] = np.mean(x.X[:, j])


                        Does this work for you?






                        share|improve this answer



























                          0














                          A simple solution would be to build a list with all the x variables and then iterate over it.



                          Maybe something like this:



                          x_list = [x1, x2, x3, x4]
                          means =

                          for i, x in enumerate(x_list):
                          for j in range(len(x.var)):
                          key = (i, j)
                          means[key] = np.mean(x.X[:, j])


                          Does this work for you?






                          share|improve this answer

























                            0












                            0








                            0







                            A simple solution would be to build a list with all the x variables and then iterate over it.



                            Maybe something like this:



                            x_list = [x1, x2, x3, x4]
                            means =

                            for i, x in enumerate(x_list):
                            for j in range(len(x.var)):
                            key = (i, j)
                            means[key] = np.mean(x.X[:, j])


                            Does this work for you?






                            share|improve this answer













                            A simple solution would be to build a list with all the x variables and then iterate over it.



                            Maybe something like this:



                            x_list = [x1, x2, x3, x4]
                            means =

                            for i, x in enumerate(x_list):
                            for j in range(len(x.var)):
                            key = (i, j)
                            means[key] = np.mean(x.X[:, j])


                            Does this work for you?







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 7 at 9:33









                            RalfRalf

                            6,86841437




                            6,86841437



























                                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%2f55040116%2frunning-a-single-for-loop-with-previously-created-numbered-variables%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







                                Popular posts from this blog

                                Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved