text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : Consider the following code : Running mypy v0.782 on the above code under Python 3.6.9 fails with the following error : However , I feel that this code should not be regarded as an error , as ZipFile.open ( ) returns a binary filehandle , which TextIOWrapper accepts . Moreover , IO [ bytes ] and BinaryIO are (... | mypy declares IO [ bytes ] incompatible with BinaryIO |
Python : What 's a shorter way of writing this if statement ? Tried : But this seems to be incorrect . What 's the correct way ? Python 3 <code> l = [ `` a '' , `` b '' , `` c '' , `` d '' , `` e '' ] if `` a '' in l and `` b '' in l and `` c '' in l and `` d '' in l : pass if ( `` a '' and `` b '' and `` c '' and `` d... | Shorter way of if statements in python |
Python : I 'm using the Python 3.5.2 shell . I am confused about why this works as it does ? The order of the operations defines that ** is executed before > which is before == so it should work . <code> 5 > 5**2False5 > 5**2 == FalseFalse ( 5 > 5**2 ) == FalseTrue | Order of operations Incorrect ? |
Python : In a python discusion , I saw a function to convert IP string into an integer in functional progamming way . Here is the Link .The function is implemented in a single line.However , I have few ideas of funcional programming . Could anybody explain the function in detail ? I 've some knowledge of `` map '' and ... | How to understand the functional programming code for converting IP string to an integer ? |
Python : Why does numpy return different results with missing values when using a Pandas series compared to accessing the series ' values as in the following : <code> import pandas as pdimport numpy as npdata = pd.DataFrame ( dict ( a= [ 1 , 2 , 3 , np.nan , np.nan , 6 ] ) ) np.sum ( data [ ' a ' ] ) # 12.0np.sum ( dat... | Numpy inconsistent results with Pandas and missing values |
Python : I am attempting to implement a simple Pygame script that is supposed to : First , check for when the user presses the Space key ; On Space keypress , display some text ; thenPauses for 2 seconds and then update the screen to its original state.Note that all of the above events must occur sequentially , and can... | Pygame Surface updates non-sequentially |
Python : I have to append elements to a list only if the current iterated element is not already in the list.vsThe list comprehension gives the result is what I want , just the returned list is useless . Is this a good use case for list comprehensions ? The iteration is a good solution , but I 'm wondering if there is ... | Is list comprehension appropriate here ? |
Python : I have a dataframe that looks like this : I want to add 3 more columns that show the ratio of positive and negative values by a certain number . For example , if the number is 8 : If the number is 5 : I 've been doing the calculation with a loop and several conditional statements and it 's pretty slow . I wond... | How to make a dataframe that shows the ratio of different types of values ? |
Python : I use a tokenizer to split french sentences into words and had problems with words containing the french character â.I tried to isolate the problem and it eventually boiled down to this simple fact : â is matched by a pattern containing ’ if it 's put in an ensemble matcher.Is there something wrong on my part ... | Python extremely puzzling regex unicode behaviour |
Python : Why ca n't I call os.stat on the special Windows file nul ? I can open it : I was hoping to check for special files like /dev/null and nul in a cross-platform way with stat.S_ISCHR and was surprised to find that I ca n't stat a file that I can open . <code> > > > import os > > > os.stat ( 'nul ' ) Traceback ( ... | os.stat on Windows `` nul '' file |
Python : I have fit a series of SciPy continuous distributions for a Monte-Carlo simulation and am looking to take a large number of samples from these distributions . However , I would like to be able to take correlated samples , such that the ith sample takes the e.g. , 90th percentile from each of the distributions ... | Is there a fast alternative to scipy _norm_pdf for correlated distribution sampling ? |
Python : I 've defined a function that receives an optional parameter , using a fractional default value : Now when typing foo ( in the IDLE shell , the tool-tip that pops out to help me complete the call reads ( x=0 < tuple > ) , instead of the expected ( x=0.1 ) . I 've never encountered this before , though I find i... | Python 's IDLE behavior while defining fractional default values to function parameters |
Python : Is it possible to cast a number behalf of a other number ? I tried this one , but type returns a string . <code> n = 1.34i = 10type ( i ) ( n ) | Cast a value with a other values type |
Python : Similar to a question asked here : SSH and telnet to localhost using pythonI 'm trying to find a solution to the following problem : From Server A ( full rights ) over Jumhost B ( no sudo ) , I want to connect to several Network devices using Python ( one after another is enough , it does n't have to be in the... | How do I use Python libs such as Paramiko for chain connections with Telnet and SSH |
Python : I have a scenario where I 'm dynamically running functions at run-time and need to keep track of a `` localized '' scope . In the example below , `` startScope '' and `` endScope '' would actually be creating levels of `` nesting '' ( in reality , the stuff contained in this localized scope is n't print statem... | Is it possible to create a dynamic localized scope in Python ? |
Python : I was just revisiting some of my code to improve the performance and stumpled over something strange : Ok it seems to have some overhead when using the power-operator ( ** ) but otherwise they seem identical ( I guess NumPy is doing that ) but then it got strange : So there is no problem but it seems a bit inc... | Wrapping np.arrays __pow__ method |
Python : I 've been learning python for my hobby and empirical research into NP-complete problems such as Subset Product . The algorithm I have works , but it 's not doing it the way I intend to do.What I 'm trying to do is to stop itertools ' combinations once it arrives to a subset product of the input variable targe... | How to make python halt once target product is found in subset ? |
Python : In Python , you can do : Is there a shorthand for this ? In other words , a way to do integer division that throws an exception if there is a remainder ? The reason I ask is that it would be convenient in situations like this : Right now I have to make temporary variables : which does not seem very pythonic.I ... | Python - throw exception if division has remainder ? |
Python : I need to find if items from a list appear in a string , and then add the items to a different list . This code works : However , the code iterates over line ( which could be long ) multiple times- as many times as there are item in _legal ( which could be a lot ) . That 's too slow for me , and I 'm searching... | Finding multiple substrings in a string without iterating over it multiple times |
Python : I 'm in doubt how the objects are stored . Say I have a class defined like : My guess is that the only thing stored in the data store is the name/value/type of some_number together with the fully qualified name of the class ( SomeEntity ) . However I have not stumbled upon any information that confirms this . ... | How are Google App Engine model classes stored ? |
Python : I want an expression whose value is a Boolean array , with the same shape of data ( or , at least , can be reshaped to the same shape ) , that tells me if the corresponding term in data is in set.E.g. , if I want to know which elements of data are strictly less than 6 , I can use a single vectorized expression... | are elements of an array in a set ? |
Python : I 'm using ropemacs and company-mode for code completion in emacs.However , I oftern found ropemacs slow , for example , when I type inThen ropemacs will try to do the completion for the methods under os modular , which will make the emacs stuck for 5~6 seconds.Is there a way to avoid this situation ? <code> i... | How to make ropemacs faster in emacs ? |
Python : Suppose I have a list : How can I iterate over the list , taking each item along with its complement from the list ? That is , would printIdeally I 'm looking for a concise expression that I can use in a comprehension . <code> l = [ 0 , 1 , 2 , 3 ] for item , others in ... print ( item , others ) 0 [ 1 , 2 , 3... | Iterate over ( item , others ) in a list |
Python : Using the C converted to python Radial Positions algorithm from this question , I have been successful in creating a radial graph based on a root node , all the way to the last child of each node . Now I have a new problem where I have multiple root nodes and will need them to be centered around the first root... | How do I make a circular tree with multiple root trees |
Python : I start with a list full of False elements.Then those elements are switched to True independently over the course of iterations.I need to know when the list is fully True . Let 's say I have 3 elements , they start asthen I check them over the iterations like : The list of elements is fixed and should not grow... | python lowest cost of checking various equalities at once |
Python : The docs for itertools.combinations state : Combinations are emitted in lexicographic sort order . So , if the input iterable is sorted , the combination tuples will be produced in sorted order.Elements are treated as unique based on their position , not on their value . So if the input elements are unique , t... | What is the guarantee made by itertools.combinations ? |
Python : I 've created an iterative function which outputs 4 3 2 1 0 1 2 3 4.If I want a recursive function that does the exact same thing , how should I think ? <code> def bounce2 ( n ) : s = n for i in range ( n ) : print ( n ) n = n-1 if n < = 0 : for i in range ( s+1 ) : print ( -n ) n = n-1 returnbounce2 ( 4 ) | Python , Make an iterative function into a recursive function |
Python : I started using TK in python to build a graphical interface for my program . I 'm not able to fix 2 issues concerning ( 1 ) the position of a button in the window and ( 2 ) use a value of a radiobutton inside a fucntion.This is my current code : I would like that the buttons `` Links '' and `` Comments '' were... | Graphical user interface with TK - button position and actions |
Python : I am running a test suite with hypothesis-4.24.6 and pytest-5.0.0 . My test has a finite set of possible inputs , but hypothesis never finishes testing.I have reduced it to the following minimal example , which I run as pytest test.pyI would expect it to try all six combinations here and then succeed . Or poss... | Why does my simple , finite hypothesis test never stop ? |
Python : I am a new user of Django , and I am trying to figure out how to created a model which can support many kind ( type ) of elements.This is the plot : I want to create a Blog module on my application.To do this , I created a model Page , which describe a Blog Page . And a model PageElement , which describe a Pos... | Create a Blog which support multiple type of post |
Python : Alright , this is doing my head in . I have two dictionaries with object groups as shown below : The output I 'm looking for is : The problem I 'm having is that I do n't know beforehand how much levels of recursion there are , as nested groups can theoretically go on infinitely . Additionally , I 'm having tr... | Recursively combine dictionaries |
Python : I need to be able to set a flag on a class ( not on an instance of a class ) which is not visible to a subclass . The question is , is it possible , and how would I do it if it is ? To illustrate , I want something like this : ... where hasattr ( Master , `` __flag__ '' ) should return True for Master but Fals... | How to add attribute to python *class* that is _not_ inherited ? |
Python : Trying to get a double-precision floating point score from a UTF-8 encoded string object in Python . The idea is to grab the first 8 bytes of the string and create a float , so that the strings , ordered by their score , would be ordered lexicographically according to their first 8 bytes ( or possibly their fi... | How to compute a double precision float score from the first 8 bytes of a string in Python ? |
Python : For larger Python packages which might interfere with other packages it is recommended to install them into their own virtual environment and some Python packages expose CLI commands to the shell.Is there a way to pip-install such a package into its own virtual environment , but have the CLI commands accessibl... | How to pip-install Python package into virtual env and have CLI commands accessible in normal shell |
Python : I have a list of sorted values that represents angles ( in degrees ) , all in the range [ 0,360 ) My goal is to find the best range ( minimum range ) that fit all the angles in the list.Some examples : Given the list angles = [ 0,1,2,10,20,35 ] the answer would be ( 0,35 ) . Given the list angles = [ 10,20,340... | find the minimum range that includes all angles in a list |
Python : I have a voxel ( np.array ) with size 3x3x3 , filled with some values , this setup is essential for me . I want to have rotation-invariant representation of it . For this case , I decided to try PCA representation which is believed to be invariant to orthogonal transformations . anotherFor simplicity , I took ... | Why my PCA is not invariant to rotation and axis swap ? |
Python : I really hope this is n't a duplicate . I tried to search for my question and I could n't seem to find it.So I have a fairly simple function that converts feet to meters : This works nicely and accepts ints , floats , arrays , and lists . However , if I put in a list ( instead of a numpy array ) , I 'd like to... | How to properly incorporate duck-typing to return original type ? |
Python : I have two lists of equal length . The first list l1 contains data.The second list l2 contains the category the data in l1 belongs to : How can I partition the first list based on the positions defined by numbers such as 1 , 2 , 3 , 4 in the second list , using a list comprehension or lambda function . For exa... | Mapping two list without looping |
Python : I have two datasets that I need to validate against . All records should match . I am having trouble in determining how to iterate through each different column . For example , in the above code , I want to compare A_1 to A_2 , and B_1 to B_2 , to return a new column , A_check and B_check respectively , that r... | Find entries that do not match between columns and iterate through columns |
Python : I have array : I would like find this pattern and return booelan mask : I use strides : I find positions of first values only : And positions another vals : Last return mask by in1d : Verify mask : I think my solution is a bit over-complicated . Is there some better , more pythonic solution ? <code> arr = np.a... | Find boolean mask by pattern |
Python : I get following result when i execute stanford parser from nltk.but i need it in the form How can I get this result , perhaps using recursive function.Is there in-built function already ? <code> ( S ( VP ( VB get ) ( NP ( PRP me ) ) ( ADVP ( RB now ) ) ) ) S - > VPVP - > VB NP ADVPVB - > getPRP - > meRB - > no... | Grammar rule extraction from parsed result |
Python : I 'm trying to plot a line over a bar chart.Here is my dataframe : When I run these two lines I get : However if I remove kind='bar ' I get three lines and if I change kind='line ' for kind='bar ' I get three bars ... <code> meh fiches ratio2007 1412 1338 0.9475922008 1356 1324 0.9764012009 1394 1298 0.9311332... | Line does n't show over barplot |
Python : Halfway through Architecture Patterns with Python , I have two questions about how should the Domain Model Classes be structured and instantiated . Assume on my Domain Model I have the class DepthMap : According to what I understood from the book , this class is not correct since it depends on Numpy , and it s... | Should Domain Model Classes always depend on primitives ? |
Python : I have to work with time series data imported from some CSVs which may look like this : As you can see , we have 3 sensors . Each sensor has its own time series with measures of temperature , humidity and pressure . However , the data is fragmented in two CSVs and it can have many gaps , etc.The objetive is to... | How to join many fragmented time series in one regular Pandas DataFrame in Python |
Python : Reading about Python coroutines , I came across this code : which curiously outputs : In particular , it misses printing the 3 . Why ? The referenced question does not answer this question because I am not asking what send does . It sends values back into the function . What I am asking is why , after I issue ... | Why does this Python generator/coroutine lose a value ? |
Python : I have a list of points with their coordinates , looking like this : What is the Pythonic way to iterate over them and choose three different every time ? I ca n't find simpler solution than using three for loops like this : So I 'm asking for help . <code> [ ( 0,1 ) , ( 2,3 ) , ( 7 , -1 ) and so on . ] for po... | Choose three different values from list in Python |
Python : I am trying to load the whole content of this link ( clicking on المزيد ) I tried so many tutorials like this one here , which teaches how to work with a similar issue ( Infinite Scrolling Pages ) .My issue is that I could n't manage to specify the load more class on this page to click it . But , if I am not m... | Clicking `` Load More '' on webpages by using python |
Python : I 'm trying to re-compile a ttf glyph-font based on it 's source svg files.I 'm using python and FontForge and struggling with converting SVG shape into FontForge 's SplineSet format . For example , this SVG fileIs represented in a font generated by FontForge as this SplineSet formatI want to create a function... | converting an SVG to FontForge 's SplineSet format |
Python : How can I match 'suck ' only if not part of 'honeysuckle ' ? Using lookbehind and lookahead I can match suck if not 'honeysuck ' or 'suckle ' , but it also fails to catch something like 'honeysucker ' ; here the expression should match , because it does n't end in le : <code> re.search ( r ' ( ? < ! honey ) su... | Regex match if not before and after |
Python : I 'm building a debugging tool.IPython lets me do stuff likeAnd it will show me the source . <code> MyCls ? ? | Given a Python class , how can I inspect and find the place in my code where it is defined ? |
Python : I am manipulating the creation of classes via Python 's metaclasses . However , although a class has a attribute thanks to its parent , I can not delete it.The execution of the above code yield an AttributeError when class B is created : Why ca n't I delete the existing attribute ? EDIT : I think my question i... | Deleting existing class variable yield AttributeError |
Python : After a few hours of isolating a bug , I have come up with the following MCVE example to demonstrate the problem I 've had : a.py : b.py : The expected output of a.py is : The actual output is : Moreover , if I create a separate module c.py , the output is as expected : Clearly , the interaction between isinst... | Why do circular imports cause problems with object identity using ` isinstance ` ? |
Python : I want to run vectorization on images using multiple GPUs ( for now my script use only one GPU ) . I have a list of images , graph and session . THe script 's output is saved vector . My machine has 3 NVIDIA GPU . Environment : Ubuntu , python 3.7 , Tensorflow 2.0 ( with GPU support ) .Here is my code example ... | How to run classify_image on multiple GPU ? |
Python : I would like to interleave multiple numpy arrays with differing dimensions along a particular axis . In particular , I have a list of arrays of shape ( _ , *dims ) , varying along the first axis , which I would like to interleave to obtain another array of shape ( _ , *dims ) . For instance , given the inputth... | Interleaving NumPy arrays with mismatching shapes |
Python : Normally a picture is gladly displayed via an ID . But in my example these images are displayed as content / character : What can I do here ? <code> .fa-calendar-alt : before { Synchro : `` \f073 '' ; | Python + Selenium - How to check an image which is styled with CSS and displayed as content ? |
Python : I 'm analyzing a set of python scripts and came across this snippet . I 'm not sure if my interpretation is correct , since I have n't come across any similar C or Java code and I do n't know Python.My interpretation goes like this : Essentially , I think the original unpack operation extracts 8 bytes , dumps ... | Verify my interpretation of this python code snippet is correct |
Python : I 'm new to programming and am learning Python with the book Learning Python the Hard Way . I 'm at exercise 36 , where we 're asked to write our own simple game.http : //learnpythonthehardway.org/book/ex36.html ( The problem is , when I 'm in the hallway ( or more precisely , in 'choices ' ) and I write 'gate... | Python ( LPTHW ) Exercise 36 |
Python : What I wantFrom a yaml config I get a python dictionary that looks like this : As you see the keyword 'subselect ' is common to all sub level and its value is always a dict , but its existance is optional . The amount of nesting might change . I 'm searching for a function , that allows me to do the following ... | Inheritance in a configuration dict |
Python : I have a list of lists which is nested in multiple layers of lists.possible inputs : [ [ [ [ 1,2,3 ] , [ a , b , c ] ] ] ] or [ [ [ 1,2,3 ] , [ a , b , c ] ] ] or [ [ [ 1,2,3 ] ] , [ [ a , b , c ] ] ] when I use flat ( ) it will just flatten everything which is not what I want . [ 1,2,3 , a , b , c ] What I ne... | python : flatten to a list of lists but no more |
Python : Running AquaEmacs , I want to execute a buffer ( C-c C-c ) in Python . The buffer starts with : The execution in AquaEmacs starts with : where test_one_liners.py is my file . This gives this error : Anyone know where and how to fix this ? Let me add the information again to make it clear . Create this buffer :... | Execute AquaMacs buffer that has `` from __future__ import ... '' |
Python : Is it possible to make either jedi.el or anaconda-mode complete base class methods ? For example , when subclassing html.parser.HTMLParser I expect it to complete the following code at point ( 1 ) ( base class has methods like handle_data or handle_starttag ) : <code> import html.parserclass MyParser ( html.pa... | Emacs : Complete base class methods for Python |
Python : So when I run this ... the error is on this line bomb=pd.DataFrame ( here,0 ) but the trace shows me a bunch of code from the pandas library to get to the error . How do I suppress all that and have the error just look like this : I just want what 's relevant to me and the last line of code that I wrote which ... | python : how to get up until the last error made by my code |
Python : I have 2 heatmaps I 'm trying to join together , one contains week over week data and the other contains 6W/YTD information . I keep them separate so their colors are n't skewed.When they 're put together in a subplot , the yaxis label on the right is the first row label on the leftI would like to remove that ... | Suppress y axis label in plotly subplot , annotation misalignment |
Python : I want to use condition GANs with the purpose of generated images for one domain ( noted as domain A ) and by having input images from a second domain ( noted as domain B ) and the class information as well . Both domains are linked with the same label information ( every image of domain A is linked to an imag... | Add class information to Generator model in keras |
Python : I 'm new with Python ( with Java as a basic ) . I read Dive Into Python books , in the Chapter 3 I found about Multi-Variable Assignment . Maybe some of you can help me to understand what happen in this code bellow : What I understand so far is the # 1 and # 2 has same output , that display the values of tuple... | Lack Understanding of Multi-Variable Assignments Python |
Python : I am trying to apply a function , cumulatively , to values that lie within a window defined by 'start ' and 'finish ' columns . So , 'start ' and 'finish ' define the intervals where the value is 'active ' ; for each row , I want to get a sum of all 'active ' values at the time.Here is a 'bruteforce ' example ... | Cumulative apply within window defined by other columns |
Python : I am writing a module that provides one function and needs an initialization step , however due to certain restrictions I need to initialize on first call , so I am looking for the proper idiom in python that would allow me to get rid of the conditional.I 'd like to get rid of that conditional with something l... | Changing a function implementation in Python |
Python : What I want to accomplish : What I have thought of so far : Is there a more Pythonic way of accomplishing this ? <code> [ a , b , c , d ] - > [ ( a , x ) , ( b , x ) , ( c , x ) , ( d , x ) ] done = [ ] for i in [ a , b , c , d ] : done.append ( ( i , x ) ) | Python turning a list into a list of tuples |
Python : I have a dataframe like below : I want the number of occurence of zeroes from df [ ' B ' ] under the following condition : expected output : I dont know how to formulate the count part . Any help is really appreciated <code> A B C1 1 12 0 13 0 04 1 05 0 16 0 07 1 0 if ( df [ ' B ' ] < df [ ' C ' ] ) : # count ... | How to count the number of occurences before a particular value in dataframe python ? |
Python : I just learned that the new walrus operator ( : = ) ca n't be used to set instance attributes , it 's supposedly invalid syntax ( raises a SyntaxError ) .Why is this ? ( And can you provide a link to official docs mentioning this ? ) I looked through PEP 572 , and could n't find if/where this is documented.Res... | Why ca n't Python 's walrus operator be used to set instance attributes ? |
Python : I 'm having trouble understanding the output of a piece of python code.The output isI ca n't for the life of me understand why it is notAny help much appreciated . <code> mani= [ ] nima= [ ] for i in range ( 3 ) nima.append ( i ) mani.append ( nima ) print ( mani ) [ [ 0,1,2 ] , [ 0,1,2 ] , [ 0,1,2 ] ] [ [ 0 ]... | Python issue with for loop and append |
Python : So I 'm making a PyGame that baseball is falling from up , and users in the bottom have to catch the ball . The balls are falling in a random speed , but I 'm having hard time getting balls falling in different speed . For example , my current code for the ball is : Here , when I run the program , the ball is ... | Python choose random number in specific interval |
Python : consider pd.Series sHow do I interpolate to get : note : I want the first and last np.nan to remainI only want to fill in values when I have values on both sides to do the the interpolation.In other words , I want to interpolate , not extrapolate . <code> import pandas as pdimport numpy as nps = pd.Series ( [ ... | pandas interpolate only when values exist on both sides |
Python : Question : Overview : I 'm looking for a vectorised way to get the first date that a certain condition is seen . The condition is found when the price in dfDays is > the target price specified in dfWeeks.target . This condition has to be hit after the date the target was set.Is there a way to do the following ... | Vectorised way to query date and price data |
Python : Lets say I have the following 2 classes in module ain module b it uses the Real classHow do I monkey patch so that when b imports Real it 's actually swapped with Fake ? I was trying to do like this in initialize script but it does n't work.My purpose is to use the Fake class in development mode . <code> class... | Python : how to monkey patch ( swap ) classes |
Python : I wrote a function that takes a degree and returns the orientation as ' N ' , 'NE ' , ... etc . Very simple , but it 's ugly - is there any way to rewrite this to make it ... prettier ? <code> def orientation ( tn ) : if 23 < = tn < = 67 : o = 'NE ' elif 68 < = tn < = 113 : o = ' E ' elif 114 < = tn < = 158 : ... | Simple , ugly function to produce an orientation from an angle . |
Python : I want to subclass a numeric type ( say , int ) in python and give it a shiny complex constructor . Something like this : This works fine under Python 2.4 , but Python 2.6 gives a deprecation warning . What is the best way to subclass a numeric type and to redefine constructors for builtin types in newer Pytho... | How to add a constructor to a subclassed numeric type ? |
Python : How do I retrieve the values of an enumerated variable v ? For example , Now , given just the above variable v , how would I retrieve a list of values [ val1 , val2 , val3 ] of v ( where val1 , val3 , val3 are expressions as above ) ? I have tried [ v.sort ( ) .constructor ( 0 ) , ... ( 1 ) , ... ( 2 ) ] but t... | retrieving value of an enumerated type in Z3Py |
Python : Imagine I have a list of tuples in this format : How could I sort the list by the first element of the tuples , and then by the second ? I 'd like to get to this list : I was thinking to do a sort for the first element , and then go through the list , and build a hash with subarrays . I will probably overcompl... | What 's the standard way of doing this sort in Python ? |
Python : I want to remove item from a list called mom . I have another list called cutHow do I remove what in cut from mom , except for zero ? My desire result is <code> mom= [ [ 0,8,1 ] , [ 0 , 6 , 2 , 7 ] , [ 0 , 11 , 12 , 3 , 9 ] , [ 0 , 5 , 4 , 10 ] ] cut = [ 0 , 9 , 8 , 2 ] mom= [ [ 0,1 ] , [ 0,6,7 ] , [ 0,11,12,3... | Python- Removing items |
Python : I am trying to create a generic Python class for a Pub/Sub type app , where the model definition specified three methods for each type of resource X that we have : I 've abstracted the code to a single method , that accepts parameters about the type and action : But this then requires me to hand-write each of ... | Writing a generic getattr ( ) and populate method parameters based on attr name |
Python : I 'm using a PolyCollection to plot data of various sizes . Sometimes the polygons are very small . If they are too small , they do n't get plotted at all . I would expect the outline at least to show up so you 'd have an idea that some data is there . Is there a a setting to control this ? Here 's some code t... | plot with polycollection disappears when polygons get too small |
Python : I want to find a way to make faster the computation of the pairwise accuracy , that is going to compare elements of the same array ( in this case it 's a panda df column ) computing their difference and then comparing the two results obtained . I would have a dataframe df with 3 column ( id of the document , J... | Faster double iteration over a single array in Python |
Python : I 'm well aware that there are differences between lists and tuples and that tuples are n't just constant lists , but there are few examples where the two are actually treated differently by the code ( as opposed to by a coding convention ) , so I ( sloppily ) have used them interchangeably . Then I came acros... | List and tuple behave differently |
Python : I think this is safe : but is this safe ? It should do the same thing because condition checking is lazy in python . It wo n't try to get the value ( and raise an exception because there 's no such key in the dict ) because the first condition is already not satisfied . But can I rely on the lazyness and use t... | Is checking if key is in dictionary and getting it 's value in the same `` if '' safe ? |
Python : I am trying to change the default error message Django generates for ArrayField ( Specifically too many items entered error message ) If a user enters too many items to my ArrayField the following message generates in the template : List contains 4 items , it should contain no more than 3.I want to change this... | How to override ArrayField default error messages in template ? |
Python : Something that can converttoor something similarand accepting in 2 or 5 <code> r '' a+| ( ? : ab+c ) '' { ( 1 , ' a ' ) : [ 2 , 3 ] , ( 2 , ' a ' ) : [ 2 ] , ( 3 , ' b ' ) : [ 4 , 3 ] , ( 4 , ' c ' ) : [ 5 ] } | is there any compiler that can convert regexp to fsm ? or could convert to human words ? |
Python : I want to simulate basic cell division using python arrays . I have u , which is an array of arrays as defined by : each u [ i ] represents a cell in the system and u is the entire system.Next , I define some functions which I will use for my cell division algorithm later . Here I am initializing my cells so t... | change one element of an array into two and then delete the original ( cell division simulation ) |
Python : Coming from a C++ world I got used to write conditional compilation based on flags that are determined at compilation time with tools like CMake and the like . I wonder what 's the most Pythonic way to mimic this functionality . For instance , this is what I currently set depending on whether a module is found... | What 's the Pythonic way to write conditional statements based on installed modules ? |
Python : I want to create some kind of descriptor on a class that returns a proxy object . The proxy object , when indexed retrieves members of the object and applies the index to them . Then it returns the sum.E.g. , This solution worked fine while I had actual arrays as member variables : Now I 've changed my arrays ... | Adaptable descriptor in Python |
Python : I 'm a newbie to Regular expression in Python : I have a list that i want to search if it 's contain a employee name.The employee name can be : it can be at the beginning followed by space . followed by ® OR followed by space OR Can be at the end and space before itnot a case sensitiveThe output from the List... | How can I use regex to search inside sentence -not a case sensitive |
Python : There are several columns in the data , three are named `` candidate_id '' , `` enddate '' , `` TitleLevel '' .Within the same id , if the enddate is the same , I will delete the lower level record.For example , given : What I want is : I will delete candidate_id=1 , enddate=2013.5.1 , and titlelevel=2.I have ... | how to use groupby to avoid loop in python |
Python : Why do instances of the object class not have a __dict__ , causing it to behave as semantically immutable ? What were the reasons for choosing this design ? Specifically , why : instances of types defined in C do n't have a __dict__ attribute by default.As noted in this question . <code> > > > a = object ( ) >... | Why are instances of the ` object ` class immutable in Python ? |
Python : I have a standard nested json file which looks like the below : They are multi level nested and I have to eliminate all the nesting by creating new objects . Nested json file . The new objects that needs to be createdMy approach : I used a normalise function to make all the lists into dicts . Added another fun... | Eliminate nesting by creating new objects from json |
Python : So lets say i have a numpy array that holds points in 2d space , like the followingI also have a numpy array that labels each point to a number , this array is a 1d array with the length as the number of points in the point array.Now i want to take the mean value of each point that have an index from the label... | Numpy split array based on condition without for loop |
Python : Is there a clever way to iterate over two lists in Python ( without using list comprehension ) ? I mean , something like this : instead of : <code> # ( a , b ) is the cartesian product between the two lists ' elementsfor a , b in list1 , list2 : foo ( a , b ) for a in list1 : for b in list2 : foo ( a , b ) | Python multi-lists iteration |
Python : I have a problem.I have list of lists that look something like this : I need sorting to be on date field ( 1st one ) , but each set of same dates must be sorted in reverse order.Resulting list must look like this : As you can see list is ordered by date but , for the same dates list is reversed.dates are still... | Python sort list of lists partially reverse based on date |
Python : I 'm working on a project where I need to create a preview of nx.Graph ( ) which allows to change position of nodes dragging them with a mouse . My current code is able to redraw whole figure immediately after each motion of mouse if it 's clicked on specific node . However , this increases latency significant... | Plotting networkx.Graph : how to change node position instead of resetting every node ? |
Python : Is there a better way to insert , one by one , elements in an array to all posible positions ( n+1 positions ) .E.g inserting [ 1 ] to [ 6 7 8 9 ] should produce : So if I insert A = [ 1 2 3 ] one by one to B = [ 6 7 8 9 ] it should produce : Currently I use numpy.roll like this : <code> [ 1 6 7 8 9 ] [ 9 1 6 ... | Insert element into numpy array and get all rolled permutations |
Python : Possible Duplicate : Python '== ' vs 'is ' comparing strings , 'is ' fails sometimes , why ? Hi . I have a question about how Python works when it comes how and when references are used.I have an example here that I understand.This makes sense . But here comes something I do n't understand.Why does a is b retu... | Python strings references |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.