text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : How can I compare each object with each and if ratio ( ) > 0.7 set possible_duplicate=True for both objects ? My try : <code> from difflib import SequenceMatcherclass Item ( models.Model ) : name = models.CharField ( max_length=255 ) desc = models.TextField ( ) possible_duplicate = models.BooleanField ( defaul... | How can I compare each object with each ? |
Python : It works in normal python interactive mode : However , the second \n is gone in iPythonWhat 's wrong ? <code> > > > `` '' '' 1 ... ... 2 '' '' '' ' 1\n\n2 ' In [ 4 ] : `` '' '' 1 ... : ... : 2 '' '' '' Out [ 4 ] : ' 1\n2 ' | iPython did n't catch the empty line as a ` \n ` |
Python : What is the pythonic way to PEP-8-ify such as with statement : I could do this but since the tempfile i/o is not with the with statement , does it automatically close after the with ? Is that pythonic ? : Or I could use slashes : But is that PEP8 comply-able ? Is that pythonic ? <code> with tempfile.NamedTempo... | Keeping 80 chars margin for long with statement ? |
Python : I have an abstract base class Bicycle : and a subclass MountainBike : The following code will cause a recursion error , but if I remove self from the super ( ) .__init__ ( self ) , the call to __str__ ( self ) : works.Question : I only discovered this error when I implemented the __str__ ( self ) : In Python 3... | Declaring Subclass without passing self |
Python : I have a list of dictionaries like this : How can I transform the above list into ? ( * ) : I tried to use .items ( ) and l [ 1 ] : However , I was not able to extract the second element position of the list of dictionaries into a list of tuples , as ( * ) <code> l = [ { 'pet ' : 'cat ' , 'price ' : '39.99 ' ,... | How to transform a list of dicts into a list of tuples ? |
Python : I have the following listI used the following to remove the hyphenThe result I got The result that Ideally want isHow can I accomplish this in the most pythonic ( efficient way ) <code> list1= [ 'Dodd-Frank ' , 'insurance ' , 'regulation ' ] new1 = [ j.replace ( '- ' , ' ' ) for j in list1 ] new1= [ 'Dodd Fran... | How to split a compound word split by hyphen into two individual words |
Python : I 'm writing a small wrapper class around open that will filter out particular lines from a text file and then split them into name/value pairs before passing them back to the user . Naturally , this process lends itself to being implemented using generators.My `` file '' classUserland codeMy code , sadly , ha... | Custom generator for file filter |
Python : I have the following dataframe : My desired result is to have : Where the unique values found in df.id become column headers ( there can be several thousand of these ) , with their latitude and longitude as values.The closest I have come is using : But I know using any sort of iteration is bad in pandas ( and ... | Create columns based on unique column values and fill |
Python : I have two data frames : df : Another data frame named allnames contains a list of names like this : I want to replace all the words in df that appear in allnames [ 'name ' ] with `` Firstname '' Expected output : I tried this : But it replaces almost 99 % of the words <code> id string_data1 My name is Jeff2 H... | How to replace a word in dataframe by using another dataframe in Pandas python |
Python : I was implementing binary search recursively in Python ( I know this is bad ) and got a max recursion error with the following code : I then changed my parameters and base case like so : This fixes the error , but I am not sure why . Can someone please explain ? <code> def bs_h ( items , key , lower , upper ) ... | Could someone explain why this fixes my recursion error ? |
Python : Directory Structure : __init__ : Views : I hope someone can explain what I am doing wrong here -I guess I 'm not understanding how to properly import app . This results in a 404 . However when views is moved back to __init__ everything works properly . <code> from flask import flask app = Flask ( __name__ ) if... | Why does my view function 404 ? |
Python : I 've got a list that contains the following : Now the ' 2/keys ' must be splitted . I figured it should be possible to make a list in a list ? But before splitting , I 've got to check if there 's a `` / '' at all.The following code , that obviously does n't work , is what I 've got : Is it possible to have a... | Splitting on / inside a list in Python |
Python : There is a code segment . running the program gets the following error The corresponding code segment is listed as follows . What can be the reason underlying it ? <code> epoch , step , d_train_feed_dict , g_train_feed_dict = inf_data_gen.next ( ) AttributeError : 'generator ' object has no attribute 'next ' i... | Getting next item from generator fails |
Python : Extract numbers followed and preceded by words : it gives the list of all words and numbers in the gives q.so now i want method to get number along with words <code> String q = 'Consumer spending in the US rose to about 62 % of GDP in 1960 , where it stayed until about 1981 , and has since risen to 71 % in 201... | Extract number followed and preceded by the words |
Python : I need to decode a string 'a3b2 ' into 'aaabb ' . The problem is when the numbers are double , triple digits . E.g . 'a10b3 ' should detect that the number is not 1 but 10.I need to start accumulating digits.If I change the while loop to this : it does work but omits the last letter.I should not use regex , on... | How do I accumulate a sequence of digits in a string and convert them to one number ? |
Python : I 'm trying to create a function that returns True is the string passed in is ' 1 ' ( valid ) or ' 1* ' ( valid ) or in the form of ' ( ' + valid + '| ' + valid + ' ) ' ( valid ) . What I mean by the last part is for example : ( 1|1 ) < - since its in the form of ' ( ' + valid + '| ' + valid + ' ) ' and ' 1 ' ... | Evaluating a string using recursion |
Python : I have two dataframes like thisI now want to populate columns prop1 and prop2 in df2 using the values of df1 . For each key , we will have more or equal rows in df1 than in df2 ( in the example above : 5 times A vs 3 times A , 2 times B vs 2 times B and 3 times C vs 1 time C ) . For each key , I want to fill d... | How to populate columns of a dataframe using a subset of another dataframe ? |
Python : I have a class that keeps track of several other classes . Each of these other classes all need to access the value of a particular variable , and any one of these other classes must also be able to modify this particular variable such that all other classes can see the changed variable.I tried to accomplish t... | Python Object Property Sharing |
Python : I have a table need to groupby by condition : When i use it gives me 13 Dm Ad 16 , which is like data being manipulated.The result I want is 13 Dm Af 16 , I know probably something wrong with 'name ' : 'first ' but how do i fix this please ? Thank you <code> R_num ORG name level13 Dm Ad 1713 Dm Af 16 df1=df.re... | Get rows corresponding to the minimum with pandas groupby |
Python : Given some classifier ( SVC/Forest/NN/whatever ) is it safe to call .predict on the same instance concurrently from different threads ? From a distant point of view , my guess is they do not mutate any internal state . But I did not find anything in the docs about it.Here is a minimal example showing what I me... | Are predictions on scikit-learn models thread-safe ? |
Python : Does Buildout support value substitution in the extends option of the buildout section ? For example , this example.cfg does n't extend with base.cfg : My goal is to send the file-to-extend as a parameter from the outside like this : I tried to merge the buildout : extends from the outside ; but that does n't ... | Does Buildout support value substitution in the extends option ? |
Python : I noticed some differences between the operations between x=x+a and x+=a when manipulating some numpy arrays in python.What I was trying to do is simply adding some random errors to an integer list , like this : but printing out x gives an integer list [ 0,1,2,3,4,5,6,7,8,9,10,11 ] .It turns out that if I use ... | numpy data type casting behaves differently in x=x+a and x+=a |
Python : This is a basic example of what I 'm talking about : Count from 0 to 10000000Now with a sort of `` status '' of the computation ( displays percentage every 1 second ) : The first example takes 3.67188 seconds , the second example takes 12.62541 seconds . I guess that 's because the scripts has to continuously ... | Python , calculating the status of computation slows down the computation itself |
Python : I 'm trying to get my programs memory footprint under control . I thought I 'd start with the imports , as I 'm only using 3-4 functions out of the rather large PyObjC library . However , I was a little surprised to see that importing specific pieces of a larger module had zero bearing on what was actually loa... | When importing , why is the entire module loaded even when only specific portions are specified ? |
Python : I have a file encoded in a strange pattern . For example , Char ( 1 byte ) | Integer ( 4 bytes ) | Double ( 8 bytes ) | etc ... So far , I wrote the code below , but I have not been able to figure out why still shows garbage in the screen . Any help will be greatly appreciated . <code> BRK_File = 'commands.BRK... | File is not decoded properly |
Python : Suppose that I have a NumPy array of integers . And I have two arrays lower and upper , which represent lower and upper bounds respectively on slices of arr . These intervals are overlapping and variable-length , however lowers and uppers are both guaranteed to be non-decreasing . I want to find the min and th... | Vectorizing min and max of slices possible ? |
Python : I have very little C experience so this may be over my head , but I am curious as I am playing around with sys.getsizeof.I tried to look at the documentation but I only found this : getsizeof ( ) calls the object ’ s sizeof method and adds an additional garbage collector overhead if the object is managed by th... | Why is there a discrepancy in memory size with these 3 ways of creating a list ? |
Python : In a Python program which runs a for loop over a fixed range many times , e.g. , does it make sense to cache range : or will it not add much benefit ? <code> while some_clause : for i in range ( 0 , 1000 ) pass ... r = range ( 0 , 1000 ) while some_clause : for i in r pass ... | Is it worth caching Python 's range ( start , stop , step ) ? |
Python : I have the following dict : When the length of a group is smaller than a minimum size ( group_size=4 ) , I want to redistribute the members to the other groups . The result in this case would be something like : I have the following code , which works , but is less efficient than I 'd like : Important note : T... | Redistribute dictionary value lists |
Python : I need a class that is an integer whose value can be changed after the object is created . I need this class to define a size that is first specified in millimeters . Later when the user-interface is created , I get a factor from the device-context that converts millimeters to pixels . This factor should chang... | Integer object whose value can be changed after definition ? |
Python : NLTK version 3.4.5 . Python 3.7.4 . OSX version 10.14.5.Upgrading the codebase from 2.7 , started running into this issue just now . I 've done a fresh no-cache reinstall of all packages and extensions , in a fresh virtualenv . Pretty mystified as to how this could be happening to only me and I ca n't find any... | Getting `` bad escape '' when using nltk in py3 |
Python : Suppose an array a.shape == ( N , M ) and a vector v.shape == ( N , ) . The goal is to compute argmin of abs of v subtracted from every element of a - that is , I have a vectorized implementation via np.matlib.repmat , and it 's much faster , but takes O ( M*N^2 ) memory , unacceptable in practice . Computatio... | Efficient elementwise argmin of matrix-vector difference |
Python : I have two dictionaries items and u_itemsI want to update the items dictionary with u_items so I did this such that I can differentiate keys from both dictionariesOutput : but when i update the items dictionary with another dictionary , let 's say n_items , it replaces the value of B_1 instead of making it B_1... | Combine two or more dictionaries with same keys |
Python : Can someone explain to me why I get < function < lambda > . < locals > . < lambda > at 0x0000000002127F28 > instead of 3 ? <code> > > > foo = True > > > bar = lambda x : x + 1 if foo else lambda x : x + 2 > > > bar ( 1 ) 2 > > > foo = False > > > bar = lambda x : x + 1 if foo else lambda x : x + 2 > > > bar ( ... | Why does this lambda function act weirdly in an else statement ? |
Python : Following other posts here , I have a function that prints out information about a variable based on its name . I would like to move it into a module.Output : I would like to put this function oshape ( ) into a module so that it can be reused . However , placing in a module does not allow access to the globals... | Acessing a variable as a string in a module |
Python : Consider this exampleoutput : how can i get : <code> def dump ( value ) : print valueitems = [ ] for i in range ( 0 , 2 ) : items.append ( lambda : dump ( i ) ) for item in items : item ( ) 11 01 | lambda in python reference mind puzzle |
Python : Here is some code to demonstrate what I 'm talking about.I would expect both expressions to yield the exact same result , but the output of this program is : What am I not understanding here ? <code> class Foo ( tuple ) : def __init__ ( self , initialValue= ( 0,0 ) ) : super ( tuple , self ) .__init__ ( initia... | Python ignores default values of arguments supplied to tuple in inherited class |
Python : I have a dataframe which looks like this : I wish to add additional columns , such as 'flag_1 ' & 'flag_2 ' below , which allow myself ( and other when I pass on the amended data ) to filter easily.Flag_1 is an indication of the first appearance of that customer in the data set . I have implemented this succes... | pandas : finding first incidences of events in df based on column values and marking as new column values |
Python : Suppose I want a class named Num which contains a number , its half , and its square.I should be able to modify any of the three variables and it will affects all of its related member variables . I should be able to instantiate the class with any of the three value.What is the best way to design this class so... | How to design a class containing related member variables efficiently ? |
Python : I have been working on a project that is using Google App Engine 's python sdk . I was digging around in it and saw a lot of methods like this.Is there any reason they assign the private variable like this ? I mean I do n't see the point of defining a method as private and then assigning it to a non private va... | Assigning variable to private method |
Python : Is there a convenient way to merge two dataframes with respect to the distance between rows ? For the following example , I want to get the color for df1 rows from the closest df2 rows . The distance should be computed as ( ( x1-x2 ) **0.5+ ( y1-y2 ) **0.5 ) **0.5 . <code> import pandas as pddf1 = pd.DataFrame... | merging pandas dataframes with respect to a function output |
Python : Say I have a DataFrameI want to grab row 2 , 5 , 6 and 10 because these are the last row for each value in Column 1 . Let 's say Column 1 is an ID and Column 2 indicates the number of that ID . I need it to pick the maximum number in Column 2 for each number in Column 1 and keep Column 3 without changing Colum... | Is there a way to grab the last item of a group |
Python : I want to take in a list of strings and sort them by the occurrence of a character using the python function sort ( ) or sorted ( ) . I can do it in many lines of code where I write my own sort function , I 'm just unsure about how to do it so easily in pythonIn terms of sorted ( ) it can take in the list and ... | Sorting a list based on the occurrence of a character |
Python : I want to do this : There 's no problem if I hard code fileName . But I need to it with fileName as a string variable and that does n't seem to work . The context of the question is that I 'm trying to make a function that has the file name as an argument . The function imports variableName from whichever file... | how do I import from a file if I do n't know the file name until run time ? |
Python : While following a C extension for Python tutorial , my module seems to missing its contents . While building and importing the module have no problem , using the function in the module fails . I am using Python 3.7 on macOS.testmodule.csetup.pyThe test and error are <code> # define PY_SSIZE_T_CLEAN # include <... | Python C Extension Missing Function |
Python : In one example of Sage math ( search for octahedral ) there is this line : What does this . < v > do ? <code> K. < v > = sage.groups.matrix_gps.finitely_generated.CyclotomicField ( 10 ) | K. < v > notation in Python 2 |
Python : I am working on a problem where I am using a nested groupby.apply on a pandas DataFrame . During the first apply I am adding a column that I am using for the second inner groupby.apply . The combined result looks faulty to me . Can anyone explain to me why the below phenomen happens and how to reliably fix it ... | Pandas nested groupby gives unexpected results |
Python : I have two sorted lists containing float values . The first contains the values I am interested in ( l1 ) and the second list contains values I want to search ( l2 ) . However , I am not looking for exact matches and I am tolerating differences based on a function . Since I have do this search very often ( > >... | Matching two lists containing slightly differing float values by allowing a tolerance |
Python : I was just toying around with an idea , and I could n't think of a way to resolve this in the backend without daunting security issues.Say I want to give users the opportunity to create simple algorithms via a webservice and test these over small lists , e.g . range ( 0 , 5 ) then report back the results back ... | Evaluating algorithms from 'untrusted ' users |
Python : I want to merge rows of dataframe with one common column value and then merge rest of the column values separated by comma for string values and convert to array/list for int values.Expecting result like : I can use groupby for column D but how can I use apply for columns A , C as apply ( np.array ) and apply ... | How to merge rows in dataframe with different columns ? |
Python : The trouble is this . Lets say we have a pandas df that can be generated using the following : then let 's suppose we would like a count of each category by month . so we go and do something like But what we 'd like to see is : Where the difference is categories that did not show up in a particular month would... | Return aggregate for all unique in a group |
Python : prints val , key , i.e . the value is evaluated first . Is this behaviourconsistent across python versions and implementations ? documented anywhere ? ( http : //docs.python.org/2/reference/expressions.html # dictionary-displays says nothing ) <code> def key ( ) : print 'key'def val ( ) : print 'val ' { key ( ... | Evaluation order of dictionary literals |
Python : I 've tried to solve my issue but I could not . I have three Python lists : My problem is to generate a Python dictionary based on the combination of those three lists : The desired output : <code> atr = [ ' a ' , ' b ' , ' c ' ] m = [ ' h ' , ' i ' , ' j ' ] func = [ ' x ' , ' y ' , ' z ' ] py_dict = { ' a ' ... | Generate Python dictionary from combination of lists |
Python : I 've got dictionaries such as : I am trying to make it so that the program can find the shortest substring in the list ( such as GAA in the first ) and use it to find all other entries that are simply extensions of GAA ( strings that start with GAA and just have extra letters ) and removes them.I know there '... | Removing all extension of a string in list |
Python : So I have strings that includes names and sometime a username in a string followed by a datetime stampI want to extract the usernames from this string.I have tried different regex patterns the closest I came to extract was followingUsing the following regex pattern <code> GN1RLWFH0546-2020-04-10-18-09-52-56394... | Regex to extract usernames/names from a string |
Python : I have 3 lists and I want to find the difference between the 1st/2nd and 2nd/3rd and print them . Here is my code : but i get only 3 as output.How to make it output 1 and 3 ? I tried using sets as well , but it only printed 3 again . <code> n1 = [ 1,1,1,2,3 ] n2 = [ 1,1,1,2 ] # Here the 3 is not found ( `` 3 '... | How to find the difference between 3 lists that may have duplicate numbers |
Python : I am writing a Java collection class that is meant to be used with Jython . I want end users to be able to manipulate the collection this way : What I find in the Python documentation is the following methods : __getitem__ and __setitem__ methods should do the job for bracket operator overloading.__iadd__ meth... | Overload instance [ key ] += val |
Python : I 'm using Python 3.8.5 . I 'm trying to write a short script that concatenates PDF files and learning from this Stack Overflow question , I 'm trying to use PyPDF2 . Unfortunately , I ca n't seem to even create a PyPDF2.PdfFileReader instance without crashing.My code looks like this : When I try to run it , I... | Ca n't open PDF file with PyPDF2 |
Python : How can I write the following code more concisely ? I know this can be written in one or two lines without using append , but I 'm a Python newbie . <code> scores = [ ] for f in glob.glob ( path ) : score = read_score ( f , Normalize = True ) scores.append ( score ) | Pythonic and concise way to construct this list ? |
Python : Any idea if it 's possible to shorten and prettify this one ( an extra variant assumes nested if-else conditions and more lists ) ? <code> some_list , some_other_list = [ ] , [ ] if condition : some_list.append ( value ) else : some_other_list.append ( value ) | How to shorten appending to different lists depending on the outcome of if statement |
Python : Let 's say I have the the following dataframe ( although the one I 'm actually working with is over 100 rows ) : For each row , I want to : In col= [ ' b ' , ' c ' , 'd ' ] , find rows where there is more than one column with value = 1 . This is my condition.Duplicate rows that meet the above condition should ... | Duplicating rows sequentially based on sum of multiple columns |
Python : I 've got two DataFrames , containing the same information ( length , width ) about different aspects ( left foot , right foot ) of the same objects ( people ) .I want to merge these into a single DataFrame , so I do this : Working with suffixes is cumbersome however . I would instead like the columns to be a ... | Pandas merge with MultiIndex for repeated columns |
Python : Currently I am doing this in my code : Then at the top of my main scripts I do this : Problem is that there are too many messages . Is there any way to restrict it to one or a few different loggers ? <code> logger = logging.getLogger ( __name__ ) logger.info ( `` something happened '' ) logging.basicConfig ( l... | How do I print out only log messages for a given logger ? |
Python : I 'd like to use some generator expressions as attributes for some expensive computation of data . If possible I would like to be able to do something like this : I would liked to have seen this print out 2 4 6 8 but this gives no output . Have I made some sort of simple mistake here ? Is what I am trying to d... | Generator expression in class not producing output I expect |
Python : I am trying to stick to Google 's styleguide to strive for consistency from the beginning . I am currently creating a module and within this module I have a class . I want to provide some sensible default values for different standard use cases . However , I want to give the user the flexibility to override an... | Most pythonic way to provide defaults for class constructor |
Python : This is my table : Now , I want to group all rows by Column A and B . Column C should be summed and for column E , I want to use the value where value C is max.I did the first part of grouping A and B and summing C. I did this with : But at this point , I am not sure how to tell that column E should take the v... | df.groupby ( ) modification HELP needed |
Python : I have a df : And it looks like this : I wish to create a new dataframe for each ID ( person 's name ) that either one column contains number 78 within the group ( no matter 78 appears in From_num or To_num or both ) , and remove the person BOTH columns does n't contain 78 , in this case 'Park ' . I have wrote... | Pandas : create a new df from another df contains specific value within group |
Python : I have a text document with 32 articles in it and I want to spot each article 's date . I have observed that the date comes on the 5th row of each article . So far I have split the text into the 32 articles using : I will like to create a list that contains the date for each article , MONTH and YEAR only : As ... | Date list in text |
Python : I 'm having trouble assigning the assignment operator.I have successfully overloaded __setattr__ . But after the object is initialized , I want __setattr__ to do something else , so I try assigning it to be another function , __setattr2__.Code : What I get : What I want/expect : <code> class C ( object ) : def... | Trouble with assigning ( or re-overloading ) the assignment operator in Python |
Python : I have two images of resolution 4095x4095 and every pixel has a different color ( no duplicate pixels within one image ) . I am trying to build a `` map '' describing the movement of each pixel between the two images.What I have now is a working , but very naive algorithm , that simply loops through all pixels... | Use numpy to quickly iterate over pixels |
Python : I know how to get the date : But is there a way where you can work out the days/hours until a certain date , maybe storing the date as an integer or something ? Thx for all answers <code> from datetime import datetimetime = datetime.now ( ) print ( time ) | Can you do sums with a datetime in Python ? |
Python : I have the following piece of code . In this , I want to make use of the optional parameter given to ' a ' ; i.e ' 5 ' , and not ' 1 ' . How do I make the tuple 'numbers ' contain the first element to be 1 and not 2 ? <code> def fun_varargs ( a=5 , *numbers , **dict ) : print ( `` Value of a is '' , a ) for i ... | Using default arguments in a function with variable arguments . Is this possible ? |
Python : I 'm working on building a python library for manipulating the lighting and programmability features of my cheap Chinese iGK64 mechanical keyboard , because the Windows driver app does n't work on Linux.I 've run the manufacturer 's driver app in a Windows VM and captured USB packets for analysis . Over the la... | What checksum algorithm do to these packets use ? |
Python : Get this simple python code , same matching with re.compile instance.I noticed that even though I am using the very same value , it creates two instances , and repeats them accordingly.I wonder if one can tell the reason for this behavior , Why does it create the second instance at all ? Why only two ? And why... | What is the reason python handles locals ( ) this way ( in pairs ) ? |
Python : Is the following safe ? Does the list comprehension evaluate first , creating a new list , and then assign that new list to x ? I was told once that changing a list while iterating over it is an unsafe operation . <code> x = [ 1 , 2 , 3 , 4 ] x = [ y+5 for y in x ] | Is it safe to assign list comprehension to the original list ? |
Python : I am working in Python . The dictionary I have looks like this : And I need to order it like this : Where the sub-dictionary with the greatest combination of exclusive key values is in the first element , the second greatest combination of exclusive key values is in the second element and so forth . The greate... | How can I get a ranked list from a dictionary ? |
Python : I am trying to run a forward pass on a convolutional neural network having a convolutional layer , followed by a pooling layer and finally a rectified linear unit ( ReLU ) activation layer . The details about input data and convolutional layer filters are as follows : X : 4-dimensional input data having shape ... | Tensorflow Placeholders vs Tensorflow Constants vs Numpy Arrays |
Python : I have trained two separate modelsModelA : Checks if the input text is related to my work ( Binary Classifier [ related/not-related ] ) ModelB : Classifier of related texts ( Classifier [ good/normal/bad ] ) . Only the related texts are relayed to this model from ModelAI wantModelC : Ensemble classifier that o... | Keras vertical ensemble model with condition in between |
Python : I seem to be running into a bug with Python 's built-in sorted function . I ca n't seem to find it documented or described anywhere , but I 'm also getting results that seem to be inherently impossible based on my understanding of Python so I 'm hoping that someone can help , or at least point me in the right ... | sorted ( ) function differing from results obtained via list comprehension |
Python : ContextI am trying to create a program that gets the product of all n pairs in a number reading from left to rightFor example , in the number 2345678 : The product of all 2 pairs would be 2*3 = 6 , 3*4=12 , 4*5=20 , 5*6=30 etc ... The product of all 3 pairs would be 2*3*4=24,3*4*5=60 , 4*5*6=120 etc ... I have... | Change length of operation depending on a value |
Python : I have a python class , and I need to add an arbitrary number of arbitrarily long lists to it . The names of the lists I need to add are also arbitrary . For example , in PHP , I would do this : How do I do this in Python ? I 'm also wondering if this is a reasonable thing to do . The alternative would be to c... | Adding variably named fields to Python classes |
Python : How can I make a string output a list ? ( Probably very simple , I know ) I have looked through all of google , and NONE of the solutions worked.My code : ( it 's a bit paraphrased ) Outputs : file1.txt file2.txt file3.txt in the Pmw.ScrolledText box.What do I need to do to make the output look like the follow... | Make a string output as a list in Pwm |
Python : I try to find way for update speсial software ( Python application ) on client.Client already have HG or GIT , and I can dictate any requirements for client environment.But client have slowly and breaking out internet connection.HG , GIT and others tools ideal for update procedure by changesets with minimal tr... | Any ways to resuming download on HG or GIT changsets pulling ? |
Python : Given an arbitrary string ( i.e. , not based on a pattern ) , say : I am trying to partition a string based a list of indexes.Here is what I tried , which does work : The split is based on a list of indexes [ 3,10,12,40 ] . This list then needs to be transformed into a list of start , end pairs like [ [ 0 , 3 ... | Efficiently partition a string at arbitrary index |
Python : I know I 'm close to figuring this out but I 've been wracking my brain and ca n't think of what 's going wrong here . I need to count the number of vowels in the array of nameList using the vowelList array , and currently it 's outputting 22 , which is not the correct number of vowels.Incidentally , 22 is dou... | Counting vowels in an array |
Python : Consider this simple class : Now if I create two instances of the class and compare their 'method ' attributes , I get different results in Python 3.7 and 3.8 : What 's going on here ? Why are the methods equal in 3.7 but not in 3.8 ? And what does this have to do with __eq__ ? <code> class A : def method ( se... | Comparing object methods leads to different results in 3.8 |
Python : I have these lists : How can I split l1 this way ? I 've tried using a function : But it 's not working ... <code> l1 = [ a , b , c , d , e , f , g , h , i ] l2 = [ 1,3,2,3 ] [ [ a ] , [ b , c , d ] , [ e , f ] , [ g , h , i ] ] -The first element is a list of one element because of the 1 of l2-The second elem... | Splitting a list to sublists with sizes given in another list |
Python : I was wondering if someone could explain why these two examples ultimately yield the same result : and : I intuitively understand the first 'if ... is None ' but I struggle with the second example . Are both ok to use ? I realise this could be quite an easy question hence if anyone could direct me to any readi... | python class default parameter |
Python : I have the perl regular expression /VA=\d+ : ( \S+ ) : ENSG/ which is used in a if statement asI am trying to figure out what the best way to replicate this in python would be . Right now I haveIs this a good way to translate it ? I guess this is one area where perl is actually more readable than python.Note t... | Which python re module to pick for translating a perl regular expression |
Python : I created a javaFX chooser file in Jython . It was n't easy to port from Java to Jython , but in the end some results came . Now I would like to parameterize the obtained class , taking into account the file filters , so as to be able to use the object for browsing different from the type of filtered files.I t... | Add file filters to JavaFx Filechooser in Jython and parametrize them |
Python : I have a Python package called Util . It includes a bunch of files . Here is the include statements on top of one of the files in there : This works fine when I run my unit tests.When I install Util in a virtual environment in another package everything breaks . I will need to change the import statements to a... | is there any point in using relative paths in Python import statement ? |
Python : I am trying to read in a Fuzzy plain text rule and pass the parameters to a SciKit-Fuzzy function call to create fuzzy rules.For example , if I read in this text rule : Then the function call will be : If text rule is : Then the function call will be : Since each rule can have unlimited number of input variabl... | Calling a function with unknown number of parameters Python |
Python : A colleague of mine mistakenly typed this ( simplified ) code , and was wondering why his exception was n't getting caught : Now I know that the correct syntax to catch both types of exception should be except ( IndexError , ValueError ) : , but why is the above considered valid syntax ? And how does it work ?... | Explanation of 'or ' in exception syntax , why is it valid syntax and how does it work ? |
Python : I am confused why FooBar.__mro__ does n't show < class '__main__.Parent ' > like the above two.I still do n't know why after some digging into the CPython source code . <code> from typing import NamedTuplefrom collections import namedtupleA = namedtuple ( ' A ' , [ 'test ' ] ) class B ( NamedTuple ) : test : s... | Weird MRO result when inheriting directly from typing.NamedTuple |
Python : I searched and I could n't find a problem like mine . So if there is and somehow I could n't find please let me know . So I can delete this post.I stuck with a problem to split pandas dataframe into different data frames ( df ) by a value . I have a dataset inside a text file and I store them as pandas datafra... | Split Pandas Dataframe Column According To a Value |
Python : From a segmentation mask , I am trying to retrieve what labels are being represented in the mask . This is the image I am running through a semantic segmentation model in AWS Sagemaker.Code for making prediction and displaying mask.This image is the segmentation mask that was created and it represents the moto... | How to retrieve the labels used in a segmentation mask in AWS Sagemaker |
Python : How come this code does not throw an error when run by the Python interpreter . Output is [ ' A ' , ' B ' , ' C ' , 'D ' , ' E ' ] . I thought Python would give me an error on the second statement since a has only 3 elements . Does this feature have any natural uses while coding ? <code> a = [ ' A ' , ' B ' , ... | Curious behaviour of Python lists |
Python : I am learning about methods like argwhere and nonzero in NumPy . It appears that thenumpy.nonzero ( x ) the function returns a tuple of one-dimensional ndarray objects so that the output of this function could be used for indexing.I have not ready the C source code of nonzero because I do n't know how to find ... | Inefficiency of Numpy Argwhere |
Python : I made a typo in my code that went completely silent syntactically.If you have n't noticed it , it 's the use of : instead of = when declaring the variable dict_args.So my question is , does the python syntax : a:1 , by itself , hold any meaning ? Or should it hypothetically be considered a syntax error ? <cod... | Should n't `` a:1 '' be a syntax error in python ? |
Python : I am fairly new to python and I 'm writing a secure ftp server/client to handle basic uploading/downloading of files ( but encrypted ) .To ensure the client has the secret key , I encrypt and send a randomized 32 byte number . The client must decrypt the number , add one , re-encrypt it , and return it to the ... | Python inconsistent error when comparing two very large numbers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.