Most voted "python" questions
Python is a dynamic and heavily typed programming language whose design philosophy emphasizes usability. Two similar but incompatible versions of Python are in use (2 and 3). Please mention the version you are using when asking a question about Python.
Learn more…8,642 questions
Sort by count of
-
4
votes2
answers245
viewsNested data class built from a dictionary
Consider the following: implementation: from abc import ABC # Base class DictModel(ABC): def __init__(self, model=None): if model: for k, v in model.items(): if isinstance(v,dict): setattr(self, k,…
-
4
votes0
answers83
viewsWhat is the best way to do a very large and repetitive task?
I need to take the duration of 18000+ audios, using the library audioread for each audio it takes right 300ms, ie at least 25~30 minutes of processing. Using a system of Queue and Process, using all…
-
4
votes1
answer217
viewsHow to set default in parameters when specifying the type of the object?
When defining functions, I usually use the feature of specifying the type of object that can be used as argument and which object the function should return. See example below: def…
-
4
votes2
answers207
viewsUse of multiple keys in Tkinter
Okay, I edited the question, this is the most simplified example, I wish that while the '6' key is being pressed, even using the '8' key, it continues to interact with the program, while '8' only…
-
4
votes1
answer536
viewsHow to check if a string is inside a string set?
In the code below I have the set of strings ('M', 'F') and soon after I ask the user to enter their gender so that the value is recorded. valores = ('M','F') print(valores) sexo = str(input('Digite…
-
4
votes1
answer237
viewsRegex for positive, negative, sum and subtraction number tokens
I have to do a lexical parser in python using the PLY. Use REGEX to pick up tokens: Example: t_FLUTUANTE = r'flutuante' The expression above gives a match with the word flutuante and return me a…
-
4
votes1
answer61
viewsHow to copy the script by running to another folder in Python?
I made a script in Python that runs some commands in the terminal, and I want it to move to another folder. I tried to use the cp teste.py minha_pasta/teste.py, but it doesn’t work. This is my code:…
-
4
votes2
answers79
viewsUsing functional programming features to remove a word list from another list
I am analyzing a literary text and am having the following problem to remove a group of words from the text. These are not repeated words. link_words are words that will disturb a later analysis of…
-
4
votes3
answers170
viewsRemove the brackets from the Sorted() function
I was creating a quadratic function calculator and wanted to lay down roots in the ascending order. Searching, I arrived at the function sorted(). raiz1 = round((-b + math.sqrt(delta)) / (2 * a), 2)…
pythonasked 4 years, 10 months ago Bernardo Lansing 121 -
4
votes1
answer402
viewsPython - does not allow assigning value to the variable in if conditional, why?
I did something in Python that is common to do in C and javascript, ie, give a value to a variable when an if condition is met. I’m sure that in Python it’s also possible to program in this way,…
-
4
votes1
answer41
viewsDoubt about "resorteio" of equal values
I did a giveaway exercise using dictionary: from random import randint from time import sleep from operator import itemgetter jogo = {'jogador 1': randint(1,6), 'jogador 2': randint(1,6), 'jogador…
-
4
votes2
answers193
viewsDefine criteria for sorting a list of lists
I have a list of lists of strings. For example a list, in which the internal lists have size n=3: listEx = [['verde','preto','laraja'], ['rosa','lilás','azul'], ['bordô','cinza','branco'], [preto,…
-
4
votes1
answer291
viewsComposition of objects in Python
In this case, I’m trying to understand how the connection between two classes and their objects. Since, when creating an object, a space in memory would be reserved for it, this space includes the…
-
4
votes2
answers108
viewsGiven an X number, check if there are 2 elements in a list that together result in X
Problem: The user enters an X number, and a function must check whether two numbers summed within a list, content elements that can be ' ' or integers, results in the user’s X number. My job: #…
pythonasked 4 years, 4 months ago Pedro Barretto 51 -
4
votes2
answers584
viewsHow do I draw random names from each list without repeating them
I want to draw random names from 3 different lists, I have a program in Python that does more or less that. The problem is that they keep repeating several names in different combinations, I would…
-
4
votes3
answers341
viewsSort a list based on two different criteria using Sorted
I have a list of tuples and I want to sort them out, but that’s two different criteria. Each tuple has the following configuration: (peso, beneficio) The ordination I want to make is as follows:…
-
4
votes1
answer161
viewsOutput composite structures in Python in Google Colab
I have this list called "brazil" and I wanted to understand why when I asked for it in Google Colab Notebook calling its respective variable, the list is presented in a certain order and when I…
-
4
votes2
answers96
viewsHow does logic test work with two integers in Python?
I was analyzing a code and came across the following expression: 1 & n >> k Where n and k are integers. For now, I’m focused on the first part of the expression. I’ve never seen a logic…
-
4
votes1
answer61
viewsDate count of days when it has turn of year
I’m having trouble generating an iteration where dates are displayed from a given day to the most current day. this problem happens when it has the "turn of the year" and I put a condition of…
-
4
votes3
answers125
viewsHow to add one column of data based on another in excel through Pandas?
I have a spreadsheet with multiple import data. The problem is always the format as the data comes. For example, I have a column called "Imported Goods" that has values like the below: 1 X 40…
-
4
votes3
answers214
viewsCalculate increments so that 2 numbers become equal
The problem: With a very creative name, the Protagonist is in his first episode of its incredible saga! In an afternoon any Z, the Protagonist’s best friend, challenged the even for a super fun…
-
4
votes0
answers47
viewsHow to format a cell number in excel for hours type through Openpyxl (Python)?
Whoa, you guys are fine? So, I’m developing a Python test API that when it’s called, it has to return me an Excel file with pre-defined data. One of these data is a time variable that must be…
-
4
votes1
answer79
viewsHow to pass a dictionary to the range() function
I was looking at the documentation (docstring) of the range function and came across the following: Init signature: range(self, /, *args, **kwargs) Docstring: range(stop) -> range object…
-
4
votes2
answers54
viewsWhy does creating a list with the same generator only work the first time?
In Python 3.6.8, when I materialize the list, it is shown and erases. This is a bug or so it is? >>> vet_neg ['EH01', 'EH02', 'EH03'] Categories (3, object): ['EH01', 'EH02', 'EH03']…
-
4
votes1
answer53
viewsRelate two dataframes using python logic
Hello, I need to relate the two dataframes below using conditions (i) if df1 cat is in the tuple of the df2 cat column; and (ii) the event column. The result should be a column 'Resp' in df1 that…
-
4
votes1
answer161
viewsAdd different scales in matplotlib
I would like a help to configure the Y-axis scale. When trying to plot a bar graph with low and high values, the smaller ones end up not appearing in the scale. I tried some options, but it does not…
-
4
votes0
answers38
viewsDo the processes executed in parallel relate to the number of Cpus nuclei?
I’m studying the module multiprocessing of Python, in which allow me to run several processes in parallel (in my understanding). As an illustration case let’s see the example below: import time from…
-
4
votes1
answer34
viewsSort with Selection Sort by size and alphabetically
I have a college exercise, but I need some help. I need to do a program that gets a list containing N nomes and returns a list of all received names sorted by size (number of letters) the Selection…
-
4
votes3
answers77
viewsGenerate multiple different arrays containing random numbers
I am developing a program and need to generate an array of 16 elements, in which each input is 0, 1 or 2; and then I need to check if this array meets certain conditions. To generate this array, I…
-
4
votes1
answer123
viewsWhat is the difference between the rest operator (%) in Python and Rust?
Writing a small program in Rust, I noticed that the operator results % are different from what I get in Python for negative numbers. For example, in Python -4 % 26 returns 22, but in Rust: fn main()…
-
4
votes1
answer49
viewsPython Any checks too many elements even returning a True option with the first
I’m having a question about how built-in any python: variavel = None any([not variavel, variavel.get("chave1"), variavel.get("chave2")]) The way I see it, if the first item on the list was True, the…
pythonasked 3 years, 7 months ago Mauro Martins Júnior 55 -
4
votes2
answers100
viewsSort two lists simultaneously, by notes in ascending order, then by name
I have created two lists, one of notes and one of names. The program must sort notes in ascending order, but it must sort names as well. I tested it as follows: notas = [5, 7, 9, 3] nomes =…
-
3
votes1
answer109
viewsHow to repeat a block of Jinja2?
I’m using the Jinja2 as a template engine to generate a static HTML site in a Python script. I want to repeat the contents of a block (title) in the layout template (html layout.), that is like:…
-
3
votes2
answers1248
viewsHandling java/python/c directories
I have an A directory, and this A directory has several subdirectories, and in each subdirectory, it has a varied number of files. I would like to put all the files in a directory in the order they…
-
3
votes2
answers14161
viewsWhat is the shortcut for code execution in Sublime Text?
How do I make the shortcut Ctrl(Cmd)+B in Sublime Text, run Python codes on the same screen as the code?
-
3
votes3
answers3281
viewsSublime Text 2 - python error message /usr/bin/python: can’t find '__main__' module in ''
Using the cmd+B (Tools -> Build) in Sublime Text 2, the following error message appears: /usr/bin/python: can't find '__main__' module in '' How to solve this?…
-
3
votes1
answer607
viewsHow to decompile code from a python module using marshal?
I would like to get the bytecode of a module in Python and save in a pyc with marshal. Example: abc test module t2 mod2 So I would import abc.test.module and would like to get the bytecode and so…
-
3
votes4
answers8851
viewsFull Python file path
I’m using the method os.listdir() to return a list of all the files, however the return is only the file name and I would like it to return the absolute path, someone knows some way ? The method…
-
3
votes2
answers1330
viewsHow to insert a variable in the middle of the address I pass to Urllib2?
I’m using the function urllib2 in Python and need to put a variable in the middle of the link I pass to function. For example: request =…
-
3
votes1
answer122
viewsHow can I call functions that are after the same function?
I have sometimes managed to call functions that are further ahead in the program. However, it takes me hours to find a way to do so. What is the easiest way? Ex: def paintball(): print "Olá" adeus()…
-
3
votes2
answers2033
viewsReturning ZIP Code data in form
I have the following problem: I am trying to fill in the fields street, city and state with the post informed. They’re all input. I’m using https://github.com/jbochi/cep My project is in Django, but…
-
3
votes1
answer966
viewsArduino UNO restarts when using serial port outside the IDE
My Arduino UNO is rebooting when I use its serial port with a Python script. But when I open the serial terminal from the Arduino IDE and run the same Python script, it works normally. Why this…
-
3
votes2
answers123
viewsHow to use two Python text decorators?
How can I make to use two decorators in python, as in the example below: @makebold @makeitalic def say(): return "Hello" returning: <b><i>Hello</i></b> I’m not trying to make…
-
3
votes1
answer892
viewsImage Manipulation - Shape Condition " image[ CONDITION ] "
I’m working with Python image manipulation. I came across a line of code like: image[dst > 0.01 * dst.max()] = [0, 0, 255] Being "image" and "dst" images. What is inside the brackets "[]",…
-
3
votes2
answers531
viewspython packages with dependency installation
I wonder if as in packages . deb for example, it is possible in my setup.py i configure the dependencies for my package, and when running: $ sudo python setup.py install They are installed…
-
3
votes1
answer152
viewsMultiple Pipelines to Treat Different Files in Scrapy
How to treat pipelines.py when we have different Piders? Example: I have a Spider that works by getting posts from a particular blog and another by saving images from jpeg banners found on each…
-
3
votes1
answer156
viewsReplace text Beautifulsoup
I have the following html: <p>Um acidente no cruzamento da rua ... </p> <div id="marca"></div> <p>Um acidente no cruzamento ......</p> <div…
-
3
votes1
answer203
viewsSeparate result in different worksheets
I have a problem in which I have to take all my information (information from each cell of the spreadsheet), make them go through a condition and for each result of the condition write in a new…
-
3
votes1
answer1222
viewsCalling another terminal with python
I’m doing a project here and I need to open another terminal window, which runs the command ls. I’ve tried with subprocess but it was a mistake: Traceback (most recent call last): File "tests.py",…
-
3
votes2
answers2574
viewsRead more than one. xls file in python
I posted a very similar question a few days ago, but this time, I’m trying to do something much more generic. I want to get the information from line 0 and 1. The code below is complete, and is…