text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : I have a list like so : I want it to look like sowhat 's the most efficient way to do this ? edit : what about going the other way ? -- > <code> [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' ] [ [ ' a ' , ' b ' , ' c ' ] , [ 'd ' , ' e ' , ' f ' ] , [ ' g ' , ' h ' , ' i ' ] ] [ [ ' a ... | python split string every 3rd value but into a nested format |
Python : I have a nested function that I 'm using as a callback in pyglet : But then I run into problems later when I need to reference the nested function again : This does n't work because of the way python treats functions : Thanks to two similar questions I understand what is going on but I 'm not sure what the wor... | Workaround for equality of nested functions |
Python : I 'm looking for optimizations on the following problem ( I 've got some working code but I 'm fairly sure it could be quicker and is written in a bad way ) . I 've got a list of SKUs ( between 6 and 9 digit numbers ) that I 'm looking up information on on Amazon . The working code is given below : where x is ... | Most efficient way to produce a Python dictionary given a list |
Python : If I take a simply and empty numpy array i can see it has 96 bytes of overhead , What is that 96 bytes storing ? Where in the C source for numpy or Python 3 ( cpython ) is this set up ? <code> > > > sys.getsizeof ( np.array ( [ ] ) ) 96 | Why does a numpy array have 96 bytes of overhead ? |
Python : Let 's say one file has 10 global constants that I want to import into another file.Instead of doing the following , is there any simpler way to import all the global constants without doing something like : from file_one.py import * . I do n't want it to import the entire file , just the global variables . <c... | How to import large number of global variables without listing each one ? ( Python ) |
Python : I 'm trying to create a regex that matches a third person form of a verb created using the following rule : If the verb ends in e not preceded by i , o , s , x , z , ch , sh , add s. So I 'm looking for a regex matching a word consisting of some letters , then not i , o , s , x , z , ch , sh , and then `` es '... | Regex for a third-person verb |
Python : Python ( and ipython ) has very powerful post-mortem debugging capabilities , allowing variable inspection and command execution at each scope in the traceback . The up/down debugger commands allow changing frame for the stack trace of the final exception , but what about the __cause__ of that exception , as d... | How to debug the stack trace that causes a subsequent exception in python ? |
Python : These are 3 dicts I made each with the 4 same keys but of course different values.I stored the dicts in a list.What I 'd like to do is loop through the list and display each like so : I was thinking a for loop would do the trick for student in students : and I could store each in a empty dict current = { } but... | Looping through a list that contains dicts and displaying it a certain way |
Python : I have a multi-index dataframe and I want to know the percentage of clients who paid a certain threshold of debt for each of the 3 criteria : City , Card and Collateral.This is a working script : And this is the result : To overcome this issue I tried the following without success : And this is the result I wi... | Count if in multiple index Dataframe |
Python : I would expect both cases to raise a TypeError , but this is not the case . Why not ? The Python documentation on this subject talks about strings , tuples and dictionaries , but says nothing about lists . I 'm a bit confused about this behavior . I 've been able to duplicate it in Python 2.7 and 3.2 . <code> ... | Why does using a list as a string formatting parameter , even with no % s identifier , return the original string ? |
Python : I have an environment of conda configurated with python 3.6 and dvc is installed there , but when I try to execute dvc run with python , dvc call the python version of main installation of conda and not find the installed libraries . <code> $ conda activate py36 $ python -- versionPython 3.6.6 : : Anaconda cus... | How to execute python from conda environment by dvc run |
Python : I have a Fargate ECS container that I use to run a Docker container through tasks in ECS . When the task starts , an sh script is called , runner.sh , This in turn starts a long-running Python script , my_python_script.py . I know the Python script is running fine because it does what it needs to do , but I ca... | How to see Python print statements from running Fargate ECS task ? |
Python : Folks , After building and deploying a package called myShtuff to a local pypicloud server , I am able to install it into a separate virtual env.Everything seems to work , except for the path of the executable ... If I try running the script directly , I get : However , I can run it via : Am I making a mistake... | running a python package after compiling and uploading to pypicloud server |
Python : The following code : outputs : However when enabling PEP 563 – Postponed Evaluation of Annotations : The output is : How can I get the exact same object of type inspect.Signature with PEP 563 like without it ? <code> import inspectfrom typing import NamedTupleclass Example ( NamedTuple ) : a : strif __name__==... | inspect.signature with PEP 563 |
Python : Say we want to import a script named user.py , which may fail.How can we make sure to only catch the possible import failure of user.py itself , and not of the imports that may be contained in user.py ? <code> try : import userexcept ImportError : logging.info ( 'No user script loaded . ' ) | How to catch an ImportError non-recursively ? |
Python : For instance , consider the case : the exception does not print the value that was out of range . My guess is that we do n't know if the __str__ function of whatever was passed in raises an exception , so we do n't touch it ? <code> > > > a = [ ] > > > a [ 12 ] Traceback ( most recent call last ) : File `` < s... | Why do python exceptions typically not print offending values ? |
Python : I 'm trying to get different college names and their rankings from a webpage . The script I 've tried with can parse the first few names and their rankings accordingly . However , there are 233 names and their rankings in that page but they can only be visible when that page is made to scroll downward . The th... | Script grabs fewer content out of many |
Python : My DataFrame has a string in the first column , and a number in the second one : What I want to do is to manipulate this DataFrame in order to have a list object that contains a string , made out of the 5th character for each `` GEOSTRING '' value , for each different `` IDactivity '' value . So in this case ,... | I need to create a python list object , or any object , out of a pandas DataFrame object grouping pieces of values from different rows |
Python : Monday 27 jul 2020 , I 'm running pytube module perfectly but after one day later its code is not working any more . It 's show 's too many values to unpack ( expected 2 ) Anyone know this ? Or other modules like this to extract YouTube captions ? <code> from pytube import YouTubeurl = input ( `` Entry url : `... | Too many values to unpack in pytube module problem |
Python : I want to implement users in my system . I know that Django already has an authentication system , and I 've been reading the documentation . But I do n't know yet the difference between And I do n't want to know why to use one or another , but what happens under the hoods . What 's the difference ? <code> fro... | Under the hoods what 's the difference between subclassing the user and creating a one to one field ? |
Python : I 'm trying to make a mapping between the grade categories in the picture below . Then I would like to be able to call a function that converts a grade to the same grade in an equivalent format . Ex : I thought of making three parallel lists for the equivalence and then the function would end up using a bunch ... | How to make a triple equivalence dictionary ? |
Python : I have made a like button powered by ajax and I have defined a function that it refresh the text . Now I want to change it for updating from font awesome fa-heart-o to fa-heart and viceversa . How can I do it ? see the code belowbase.htmland button like htmlThank you for your help . <code> < script > $ ( docum... | Toggle icon on Like with Javascript |
Python : I 'm looking for a way to automatically produce an abstract , basically the first few sentances/paragraphs of a blog entry , to display in a list of articles ( which are written in markdown ) . Currently , I 'm doing something like this : to just grab the first few lines worth of text , but i 'm not totally ha... | Computing article abstracts |
Python : Is there any difference , subtle or not so subtle , between the effects of the following import statements ? I have found both used in example programs and sure enough , they both seem to work . It would go against the grain of Python 's `` there is only one way to do stuff '' if they were totally equivalent i... | Pythonic way to import modules from packages |
Python : Question motivation : In standard numerical languages of which I am aware ( e.g . Matlab , Python numpy , etc . ) , if , for example , you take the exponential of a modestly large number , the output is infinity as the result of numerical overflow . If this is multiplied by 0 , you get NaN . Separately , these... | Do numerical programming languages distinguish between a `` largest finite number '' and `` infinity '' ? |
Python : I was investigating Python generators and decided to run a little experiment.Memory usage ( using psutil to get process RSS memory ) and time taken ( using time.time ( ) ) are shown below after running each method several times and taking the average : I noticed that producing a generator by using xrange is co... | Why is a generator produced by yield faster than a generator produced by xrange ? |
Python : There are already a bunch of answers that solve how to do this general thing , but my main question is Why doesnt this approach work ? I am trying to `` live stream '' the stdout and stderr from a subprocess . I can do this by doing : and this works giving me the result : However this causes a problem as it re... | python stream subprocess stdout and stderr zip doesnt work |
Python : I have an array of strings grouped into three fields : I would like to convert to a numerical array ( of type np.int8 for a preference , but not required ) , shaped 4x3 , instead of the fields.My general approach is to transform into a 4x3 array of type 'S2 ' , then use astype to make it numerical . The only p... | converting numpy array of string fields to numerical format |
Python : I have an image with a missing part that I know has been coloured in green ( first image ) . What is the most pythonic way of generating another `` boolean '' image that shows white for the missing parts and black for the non-missing parts ( second image ) ? Is it possible to do it without a for-loop , but jus... | What is the most pythonic way of generating a boolean mask of an RGB image based on the colour of the pixels ? |
Python : Part of a models objective is weighted by items in a scalar list.I am solving for this by using a list of 0-1 range variables , and then using LinearExpr.ScalProd to weight the objective.Is there a way to do this with just one integer variable ( other than the objective variable ) , where I can either use a la... | Is it possible to compute argmax with or-tools with just one integer variable ? |
Python : What is the most pythonic and correct way of doing composition aliases ? Here 's a hypothetical scenario : AFAIK with # 1 my tested editors understand these just as fine as # 2 - auto completion , doc strings etc . Are there any down-sides to # 1 approach ? Which way is more correct from python 's point of vie... | Pythonic way of doing composition aliases |
Python : I 'm a Python beginner and I am from C/C++ background . I 'm using Python 2.7.I read this article : A Beginner ’ s Guide to Python ’ s Namespaces , Scope Resolution , and the LEGB Rule , and I think I have some understanding of Python 's these technologies.Today I realized that I can write Python code like thi... | Python : Variables are still accessible if defined in try or if ? |
Python : I want to initialize a list in python . I do not understand why the code below does not work : There are other ways to initialize the list , like : But , my question is why the first code does not work.Edit : I am a newbie to Python , and programming . Unfortunately I do not understand some parts of your answe... | initializing members of a list |
Python : I 'm doing some work with logs . Need to calculate a sum of time duration when the process was running without long interruptions . Set the maximum possible interruption to 30 seconds . Logs are emitted every 3 seconds.So , for example if it was running since 10:20:00 ( hours ) to 10:30:00 and was interrupted ... | python 3.6 sum of the short periods between timestamps |
Python : I have a local GitLab installation that comes with a local PyPI server to store company internal Python packages.How can I configure my PyPI to search packages in both index servers ? I read about .pypirc / pip/pip.ini and found various settings but no solution so far.Most solutions permanently switch all sear... | How to setup two PyPI indices |
Python : I 've really tried to start isolating my unit tests so I can pinpoint where errors occur rather than having my entire screen turn red with failures when one thing goes wrong . It 's been working in all instances except when something in an initializer fails.Check out these tests : I 'm mocking dependent method... | Good way to isolate tests that depend on an initializer |
Python : I 'm relatively new to python , so I 'm not even sure if I 'm approaching this in the correct way . But I have n't found a good solution anywhere.In order to avoid very ugly and repetitive code , i want to loop the elif part of the if statement.This is the ugly code i want to fix : As you can see , the index i... | Python : Loop through the elif section of an if statement |
Python : So I have a list of dictionaries like so : Of course , this is not the exact data . But ( maybe ) from my example here you can catch my problem . I have many records with the same `` Organization '' name , but not one of them has the complete information for that record . Is there an efficient method for searc... | Sort a list of dictionaries while consolidating duplicates in Python ? |
Python : The input parameters are a list of tuples representing the intervals and a list of integers . The goal is to write a function that counts the number of intervals each integer is present in and return this result as a associative array . So for example : Other example : How would I go about writing a function t... | How to count the presence of a set of numbers in a set of intervals efficiently |
Python : Suppose I have a list L of unknown objects , O1 to On , and I want to remove another object reference M which may refer to one of the objects in L , I 've managed to do it using : which is lovely and idiomatic ... but I 'm having to do it a lot , and I wonder if there 's not another more idiomatic way , or if ... | Fastest or most idiomatic way to remove object from list of objects in Python |
Python : I am going to write a set of scripts , each independent from the others but with some similarities . The structure will most likely be the same for all the scripts and probably looks like : For each script , I would like to write documentation and export it in PDF . I need a library/module/parser which reads t... | Documenting and detailing a single script based on the comments inside |
Python : Problem ContextI am trying to create a chat log dataset from Whatsapp chats . Let me just provide the context of what problem I am trying to solve . Assume message to be M and response to be R. The natural way in which chats happen is not always alternate , for e.g . chats tend to happen like this [ M , M , M ... | Is there a better way to concatenate continuous string elements in Python ? |
Python : I 'm a newcomer to Python but I understand that things should not be done this way , so please consider the following code snippets as purely educational : - ) I 'm currently reading 'Learning Python ' and trying to fully understand the following example : I did not understand if this behavior was somewhat rel... | List modification in a loop |
Python : I want to know whether a generated sequence has fewer than 2 entries.My inefficient method is to create a list , and measure its length : Obviously , this consumes the whole generator.In my real case the generator could be traversing a large network . I want to do the check without consuming the whole generato... | How to know a generated sequence is at most a certain length |
Python : When attempting to make a cross-compatible order preserving QueryDict subclass : Output on Python 3.x ( correct and expected result ) : Output on Python 2.7 ( this querystring was corrupted ) : Why does this idea work on Python 3 but not on Python 2 ? Django v1.11.20 . <code> from collections import OrderedDic... | Creating an order-preserving multi-value dict for Django |
Python : I 'm developing an application using Flask . I want a quick , automated way to add and remove debug=True to the main function call : Development : Production : For security reasons , as I might expose private/sensitive information about the app if I leave debug mode on `` in the wild '' .I was thinking of usin... | What Unix tool to quickly add/remove some text to a Python script ? |
Python : I want to process every line in my log file , and extract IP address if line matches my pattern . There are several different types of messages , in example below I am using p1andp2 ` .I could read the file line by line , and for each line match to each pattern . ButSince there can be many more patterns , I wo... | python3 : extract IP address from compiled pattern |
Python : I am reading the faster-rcnn code of tensorflow models . I am confused with the use of tf.stop_gradient.Consider the following code snippet : More code is here . My question is : what happens if tf.stop_gradient is not set for proposal_boxes ? <code> if self._is_training : proposal_boxes = tf.stop_gradient ( p... | What happens if tf.stop_gradient is not set ? |
Python : I was reading about Default Parameter Values in Python on Effbot . There is a section later in the article where the author talks about Valid uses for mutable defaults and cites the following example : I have n't been able to locate how this causes fast/highly optimised execution of code . Can somebody enlight... | How does local rebinding of global names in Python make code faster/optimized ? |
Python : Lets say that I have MyModel that has created_at and name fields . created_at is DateTime.Lets say that I have the following model objects : I want to make query that will return to me these models in this order : I want to group all models by created_at field , but only using Date part of DateTime field . I k... | Django , how to group models by date ? |
Python : Why is this ? I expected a ( ) , b ( ) , c ( ) , to be 1 , 4 , and 9 . <code> l = [ 1 , 2 , 3 ] a , b , c = [ lambda : n*n for n in l ] a ( ) # = > 9b ( ) # = > 9c ( ) # = > 9 | Confused by lexical closure in list comprehension |
Python : From a runtime efficiency perspective in python are these equally efficient ? VSI have a more complex problem that can essentially be boiled down to this question : Obviously , from a code length perspective the second is more efficient , but is the runtime better as well ? If they are not , why not ? <code> x... | Is splitting assignment into two lines still just as efficient ? |
Python : I am writing an interpreter in python and I am following this example http : //www.dabeaz.com/ply/example.htmlI would like to know how I can implement multiple assignment such as : a=b=c=1 and a= ( b=1 ) *1I have tried a few rules but all in vain . I know the parsing should be something like this.I am just not... | How to implement multiple assignment in an interpreter written in python ? |
Python : I have a function f that produces a PS1 prompt for python , set as such : Following the instructions in the documentation , I ended up with the following : However , this does n't work , since f returns a string with color codes , which python prints directly to the terminal , leading to a colorful prompt , wh... | How to reuse an existing sys.ps1 formatter in an IPython prompt ? |
Python : i have a edit_profile view at my django application that also checks if the pgp key the users saves to his profile is in RSA format , Anyways if i add a profile avatar for the very first time it works like a charm , if i want to clear or delete it , im always jumping onto the execpt block and the user avatar r... | Django unable to delete/clear data on form |
Python : I have a numpy array arr . It 's a numpy.ndarray , size is ( 5553110 , ) , dtype=float32.When I do : Why is the first comparison getting it wrong ? And how can I fix it ? The values : Is the problem with precision ? <code> ( arr > np.pi ) [ 3154950 ] False ( arr [ 3154950 ] > np.pi ) True arr [ 3154950 ] = 3.1... | Array comparison not matching elementwise comparison in numpy |
Python : Say I have an array of atoms like this : ( the length may be any ) And I want to create a list of sets that can be made with them : Is it possible to do it easily in python ? Maybe it 's very easy to do , but I 'm not getting it myself.Thank you . <code> [ ' a ' , ' b ' , ' c ' ] [ [ ' a ' ] , [ ' b ' ] , [ ' ... | Create a list of sets of atoms |
Python : my purpose of this code is to extract all the integers from the text and sum them up together.I have been looking for solutions to pluck out all the integers in a line of text . I saw some solutions suggesting to use \D and \b , I just got started with regular expression and still unfamiliar with how it can fi... | Find all occurrences of integer within text in Python |
Python : I 'm trying to run some calculation in loop , each calculation creates , uses and closes a pool . But the calculation only runs once and then throws an error : `` Pool not running '' . Of course the old one is not running , but should n't the new one be created ? Below is a simplified example , similar to my c... | Multiprocessing in a loop , `` Pool not running '' error |
Python : Executing the following mergeresults in this data frame : Why does Pandas take the index from the right data frame as the index for the result , instead of the index from the left series , even though I specified both a left merge and left_index=True ? The documentation says left : use only keys from left fram... | Setting the index after merging with pandas ? |
Python : Python 3 integers have unlimited precision . In practice , this is limited by a computer 's memory.Consider the followng code : This will obviously fail . But what will be the result of this ? The entire RAM ( and the page file ) filled with this one integer ( except for the space occupied by other processes )... | Python Infinite Integers |
Python : I have an input.pdf which is `` normal '' ( a number of pages all the same orientation and direction ) and I want to create a new pdf which can arbitrarily rearrange the input pagesFor example : I only need rotation and scaling . Each input page will be present in its entirety as some component of the output .... | How can I arbitarily rotate , rearrange etc pdf pages in Python ? |
Python : Lets say I have a tuple generator , which I simulate as follows : For this specific generator , I wish to write a function to output the following : So I 'm iterating over three consecutive items at a time and printing them , except when I approach the end . Should the first line in my function be : In other w... | Accessing consecutive items when using a generator |
Python : I 've got an endpoint built with Django Rest Framework , to which I now want to add permissions so that only users belonging to a certain group can access an endpoint . So I 'm using token based access and inspired by this example I 'm trying to use the following code : But unfortunately I get anAttributeError... | Why does n't my request.user have groups in Django ? |
Python : I have a df and I want to grab the most recent row below by CUSIP.I am using : I want this : Instead I am getting : How do I get last ( ) to take the last row of the groupby including the NaN 's ? Thank you . <code> In [ 374 ] : df.head ( ) Out [ 374 ] : CUSIP COLA COLB COLC date 1992-05-08 AAA 238 4256 3.5233... | Groupby - taking last element - how do I keep nan 's ? |
Python : Suppose I want to create a CLI that looks like thisHow would I do this ? I 've tried doing something like this -when I run cliName user create , the print statements do not run . Nothing runs . <code> cliName user createcliName user update @ click.group ( ) def user ( ) : print ( `` USER '' ) pass @ user.comma... | Creating hierarchical commands using Python Click |
Python : Consider the following scenario : You have a module M defined in m.py containing a function f.It can be called like this : The module grows to a size where it is impractical to have in a single file . You split M up into submodules M.X , M.Y , M.Z and put the following in M/__init__.py : The original code stil... | How do I prevent users from importing x from a submodule when it exposed in the parent using __all__ |
Python : I have big file ( few GBs ) with text.For example , it have next text : I need to insert word `` funny '' at 5 position , and offset the rest of text : How I can do n't read all file for offsetting rest ? Or how I can optimise this operation ? Thanks . <code> Hello , World ! Hello , funny World ! | string insertion in big file |
Python : I am running a website application and am using Flask which queries a mongodb database using mongoengine . Am getting an error when the application tries to query the database.I have mongodb installed in one of the containers and I can connect to it successfully.Docker SetupPython setup : Error occurs when I d... | Flask app unable to query data from mongodb using mongoengine in a dockerized setup |
Python : IntroductionI have a function func which is vectorizable , and I vectorize it using np.frompyfunc . Rather than using a nested for loop , I want to call it only once , and thus I 'll need to pad the inputs with np.newaxis's.My goal is to get rid of the two nested for loops and use the numpy.array broadcasting ... | A broadcasting issue involving where to put the padding |
Python : I have created a script that scrape website : 1688.com and the problem is , the site is in Chinese so whenever i try to retrieve the text , it gives me a bunch of unicode and when i export to a CSV file , there 's nothing in the file.My code : for item in lst : writer_content.writerow ( [ item ] ) The output i... | Unable to retrieve Chinese texts while scraping |
Python : I 'm having difficulties in understanding the concept of how Python reads a file when it was deleted after being open'ed . Here is the code : Text and binary modes give the same result . I tried this also for big files with more than 1Gb size and they were also read after being deleted . The operation of open ... | How Python reads a file when it was deleted after being opened |
Python : I am using itertools.product to find the possible weights an asset can take given that the sum of all weights adds up to 100 . The above code works , but it is too slow as it goes through the combinations that are not acceptable , example [ 50,50,50,50,50 ] eventually testing 3125 combinations instead of 121 p... | Any way to speedup itertool.product |
Python : Consider following codeWhat I am trying to in this code is to randomly split my data in Sales Sframe ( which is similar to Pandas DataFrame ) into roughly 4 equal parts.What is a Pythonic/Efficient way to achieve this ? <code> one , two = sales.random_split ( 0.5 , seed=0 ) set_1 , set_2 = one.random_split ( 0... | Efficient splitting of data in Python |
Python : My project consists of several django applications that need to be deployed differently , possibly on different machines . However often these apps occasionally need to access each other 's models , so I was thinking of `` externalizing '' my models so that they can be accessed more elegantly from any app . So... | Is it a good programming practice to separate models from the rest of the application |
Python : According to the Documentation : The current implementation keeps an array of integer objects for all integers between -5 and 256 , when you create an int in that range you actually just get back a reference to the existing object . So it should be possible to change the value of 1 . I suspect the behaviour of... | Comparing two variables with 'is ' operator which are declared in one line in Python |
Python : I have found an interesting performance optimization . Instead of using all ( ) : I have profiled that it 's faster when a loop is used instead : With all ( ) the profiler shows 1160 additional < genexpr > calls : With the for loop , there are no < genexpr > calls : My question is where does the difference com... | all ( ) vs for loop with break performance |
Python : I have the following class which is being subclassed : I then have a specific manager for various database . And I can call those like this : However , is there a way to do the following instead ? Basically , I want to be able to call things in reverse order , is that possible ? <code> class ConnectionManager ... | Python : How to subclass while calling parent class ? |
Python : Using Python , is it possible to insert from ss into pp and maintain pp sorted by two attributes , let 's say by the2nd then 3rd position in order to have the following result ( both attributes ascending ) : Or ( both attributes descending ) : I do n't want to use the following two statments after the loop whi... | Maintain a list sorted by multiple attributes ? |
Python : From my understanding , function and class scopes behave pretty much the same : When , however , I define a closure , behaviors are different . A function simply returns the local binding , as expected : whereas in a class the binding appears to be lost : Can anyone explain the discrepancy ? <code> > > > def x... | Closures in a class scope |
Python : I have a string that is the full year followed by the ISO week of the year ( so some years have 53 weeks , because the week counting starts at the first full week of the year ) . I want to convert it to a datetime object using pandas.to_datetime ( ) . So I do : and it returns : which is not right . Or if I try... | Formatting string into datetime using Pandas - trouble with directives |
Python : I have a COVID-19 reporting web app hosted on Heroku ( http : //www.rajcovid19.info ) , the data for which I get from the John Hopkins University Git Repository . I have added the repository as a submodule of my main project repository which I use to push changes to Heroku . This enables me to pull updates to ... | How to automatically pull the latest commit from a git submodule on Heroku ? |
Python : I frequently find myself with a list that looks like this : What is the most pythonic way to convert specific strings in this list to ints ? I typically do something like this : The above approach seems wrong . Are there better way to convert only certain items in lists to integers ? <code> lst = [ ' A ' , ' 1... | Converting subset of strings to integers in a list |
Python : I am trying to retrieve the questions , comments on questions , and answers of questions related to Python from stack overflow using Stack exchange API . I want to extract all information including body of text of questions , comments , and answers . For extracting questions , I am using following code : This ... | Retrieving text body of answers and comments using Stackexchange API |
Python : I have the following snippet : The idea is to dynamically create one class method ( like notify_fan_mail ) for each feed type . It works almost great , the only problem is that the print statement always prints `` notifying new_event '' , regardless of the method I call ( same for notify_new_mail , notify_revi... | Dynamically adding class methods to a class |
Python : I am new to python so apologies for the naive question . I have a list and another list of tuples I want to output a list l3 of size l1 that compares the value of l1 to the first co-ordinates of l2 and stores the second co-ordinate if the first co-ordinate is found in l1 , else stores 0.output : I tired to do ... | Compare a list to a list of tuple to get another list |
Python : I need to stop running my threads after a period of time , In this example I put only 120 seconds . I try by using this methods by it does not work . <code> from threading import Threadfrom Queue import Queueimport osimport timetimeout = 120 # [ seconds ] timeout_start = time.time ( ) # while True : def OpenWS... | How to stop running my threads after a period of time ? |
Python : I am writing a script that , if an array 's elements are the subset of the main array , then it print PASS , otherwise , it print FAIL instead.What should I add to my if-else statement below to make it works ? <code> a = [ 1,2,3,4,5 ] b = [ 1,2 ] c = [ 1,9 ] # The Passing Scenario if ( i in a for i in b ) : pr... | Simple if-else statement in Python |
Python : I have observed a very strange behavior of nosetests when using the @ mock.patch.object function : When I run multiple tests at the same time I get different results than when I run them individually . Specifically , it happens , that the override with @ mock.patch.object seems to have no effect , in certain c... | Running multiple tests cause interference in nosetests when patching with @ mock.patch.object and sometimes also when using ` with mock.patch.object ` |
Python : I 'm trying to extract rows from a df based on multiple conditions , ALL of the conditions must be met before any rows are selected else nothing . My dfMy conditions which must be in this format : Expected output : <code> columns = [ 'is_net ' , 'is_pct ' , 'is_mean ' , 'is_wgted ' , 'is_sum ' ] index = [ ' a ... | get subsection of df based on multiple conditions |
Python : How can I start REPL at the end of python script for debugging ? In Node I can do something like this : Is there any python alternative ? <code> code ; code ; code ; require ( 'repl ' ) .start ( global ) ; | How to start REPL at the end of python script ? |
Python : I want to do a simple thing : monkey-patch datetime . I ca n't do that exactly , since datetime is a C class.So I wrote the following code : This is on a file called datetime.py inside a package I called pimp.From the error message I 'm given : I assume that I ca n't have a module called datetime importing any... | Python pimping / monkey-patching |
Python : Given a list of strings like : I need to extract all integers with length 4 between separators # or @ , and also extract the first and last integers . No floats.My solution is a bit overcomplicated - replace with space and then applied this solution : Is it possible to change the regex for not using re.sub nec... | Extract integers with specific length between separators |
Python : For example , here is my function : and when I : call Test ( ) , what I see is `` ^ @ ^ @ '' .Why would this happen and how can I use the origin '\n ' ? <code> function ! Test ( ) python < < EOFimport vimstr = `` \n\n '' vim.command ( `` let rs = append ( line ( ' $ ' ) , ' % s ' ) '' % str ) EOFendfunction | Why would `` \n '' become `` ^ @ '' when writing Python in a .vim file ? |
Python : I have a Python program that uses Pytables and queries a table in this simple manner : To reduce the query time , I decided to try to sort the table with table.copy ( sortby='colname ' ) . This indeed improved the query time ( spent in where ) , but it increased the time spent in the next ( ) built-in function... | Why is querying a table so much slower after sorting it ? |
Python : Joining a list containing an object - is there any magic method I could set to convert the object to a string before join fails ? I tried __str__ and __repr__ but neither did work <code> ' , '.join ( [ … , Obj , … ] ) | Is any magic method called on an object in a list during join ( ) ? |
Python : Is there a way to get the complement of a set of columns using itemgetter ? For example , you can get the first , third , and fifth elements of a list using Is there a ( simple and performant ) way to get all of the elements except for the first , third and fifth ? <code> from operator import itemgetterf = ite... | Itemgetter Except Columns |
Python : Given a file looks like this : The first field is an ID which is in range ( 0 , 200000000 ) . The second field represents a type , which is in range ( 1 , 5 ) . And type 1 and type 2 belong to a common category S1 , while type 3 and type 4 belong to S2 . One single ID may have several records with different ty... | How to improve performance of this counting program ? |
Python : I have a very simple Python question , with examples using Django . When running a Python script , do I always have to precede the script filename with the python command ? In the Django tutorial I am following , some commands are as follows : However , other are like this : Why does the top one not need the p... | Differences in the ways to running Python scripts |
Python : I am self learning python and I was doing an exercise , the solution to which was posted in this thread . Could anyone translate into english what this piece of code means ? When I learned if statements I never came across this syntax . <code> consonants = 'bcdfghjklmnpqrstvwxz ' return `` .join ( l + ' o ' + ... | What is this piece of code doing , python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.