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
-
3
votes1
answer65
viewsPCA method for Feature Selection - How do I resolve the raise Exception("Data must be 1-dimensional" error)?
I am trying to implement the PCA method for Feature Selection from the following functions: #Função que permitirá rankear as features mais importantes em um barhplot def ranks_PCA (x_train, y_train,…
-
3
votes2
answers339
viewsHow to remove an object from a list during an iteration over the list itself
I need to remove an item from a list during an iteration over the list itself. The reason to remove during the loop is that if this item remains may end up triggering other triggers within the loop…
-
3
votes2
answers1637
viewsHow to print 4 triangles patterns next to each other in Python?
I need to write a program that prints 4 triangles patterns, one next to the other, separated by three horizontal spaces, as in this image below: To solve this, I wrote the following code: for i in…
-
3
votes1
answer629
viewsKeyerror: '>R' in Google Colab Python
I copied the following code from a data visualization tutorial in Python, but it does not perform properly, warning Keyerror as seen in the title. Can someone help me? There’s something wrong there?…
-
3
votes2
answers261
viewsPython Mysql Connector 2 cursor
I just started with python and I’m trying that: import mysql.connector mydb = mysql.connector.connect( infos.. ) cursor = mydb.cursor(buffered=True) cursor2 = mydb.cursor() query = ("SELECT * FROM…
-
3
votes1
answer98
viewsWhy when ordering a list with Sort(), returns None?
The following script sorts a dictionary: d = {'a': 10, 'g': 15, 'c': 67, 'z': 90, 'e': 144} ordenada = list(d.keys()) # gera uma lista das chaves do dicionário (protegida por uma tupla)…
-
3
votes3
answers183
viewsRemove repeated elements using two lists
How would you remove without using collections and while, only with for. I wanted a search structure element by element, because I already know how to remove this way. So I want to use at least two…
-
3
votes2
answers399
viewsExtracting words from a long text and creating statistics on them. What’s wrong?
We have the book "Pride and Prejudice by Jane Austen" of the project Gutenberg: http://www.gutenberg.org/ebooks/1342 The goal is to extract all the words of the text, creating statistics such as:…
-
3
votes1
answer179
viewsPrinting tabular form lists with generators
I have a list that represents 5 one-month periods with 31 days, and each period contains daily target values for a retail seller. Only for elucidation purposes would the empty structure be like…
-
3
votes1
answer689
viewsMemory release in python dictionaries
I’m trying to develop a program that temporarily stores a significant amount of variables. These variables are stored in RAM memory, inside dictionaries. But I’m having a hard time understanding how…
-
3
votes2
answers852
viewsInsert elements in the correct position in an ordered list
I wonder why this code does not work for the exercise below, because when it comes to the values that will be intermediate in the list, they end up being reversed (the example I used to test if it…
-
3
votes1
answer183
viewsPython recursive method that returns how many times a given element appears in a vector
I want to make a recursive method in Python that returns how many times an element appears in an array. Below follows my code using binary search: def binaryrec(valor, itens, menor, maior): vezes =…
-
3
votes1
answer40
viewsToggler doesn’t work
I am studying Django and found the following problem when using the staticsfiles, the Toggler that appears when the screen is reduced does not extend my bootstrap navbar, I did not find the error.…
-
3
votes1
answer749
viewsError in kivy installation
I can’t install the kivy on my computer, I’ve never touched Pip before, I’m putting the commands on cmd and gives error. I am running the following commands: python -m pip install docutils pygments…
-
3
votes2
answers168
viewsPython 3: How to understand this string
I have a question, I am a beginner and I am reading the book "Introduction to Programming with Python" 3° Edition. And I came across this code below. Program 4.3 - Income Tax Calculation salario =…
-
3
votes2
answers349
viewsHow to calculate the result of an arithmetic expression contained in a tuple respecting the operators' precedence?
I have a tuple containing the tokens of an arithmetic expression: ('5', '+', '2', '*', '5'). I tried to calculate the result of the expression, but it is not respecting the precedence of the…
-
3
votes3
answers1081
viewserror install virtualenv in python
I can’t create virtualenv, I did a search teaching how to install and when I run the install from it this error here Python version 3.8.3 > root@AlexPc:/# apt install python3-virtualenv Lendo…
-
3
votes3
answers116
viewserror in Count function
The function count is always showing the result 0, someone can help me? nome = [] voto = [] aux = 1 while aux != 0: nome = str(input("Qual é o seu nome? ")) aux = int(input("Qual é o melhor sistema…
pythonasked 4 years, 6 months ago Kevin Jordan 43 -
3
votes1
answer177
viewsPython List Invert Values
I am trying to invert two values within a nested list. Example: In the list list there are two values [[1,11],[2,22],[3,33],[4,44]] and would like to reverse the values for…
-
3
votes3
answers95
viewsDifference between creating a list with each iteration and using a list comprehension
I need to calculate the distance between the points (0,0) and (1,1). For that, I wrote the following code: def distance(x, y): if len(x) != len(y): return "x and y não possuem o mesmo comprimento"…
-
3
votes1
answer99
viewsCoding Problem Between Javascript Client and Python Server
I have a server socket in Python, follow the code: from socket import * host = '127.0.0.1' port = 6060 try: server = socket(AF_INET, SOCK_STREAM) server.bind((host, port)) server.listen(5)…
-
3
votes0
answers35
viewsHow does the Python identity operator work?
I’m starting in Python and would like to ask a question based on the code below: Case 1 x = 5 y = 5 print(x is y) # retorna True Case 2 x = "carro" y = "carro" print(x is y) # retorna True Case 3: x…
-
3
votes2
answers293
viewsReplace string chunk between 2 indexes
I have a long string inside a txt file, for example, let’s say my string is about that: strg = '123456 BANANA 00 SP' In position 14 and 15 we have the "00", I’m gonna need to replace up front The…
-
3
votes1
answer46
viewsHow to print/insert in an organized way inside a csv file a tuple in Python
Would anyone know how to print a tuple as follows: amount_of_commits,author 148, Steve Ellis 2, Alex Kwiatkowski 2, Thomas 1, Dan Forbes 1, David Parker 1, John Barker 1, Thomas Hodges…
-
3
votes1
answer170
viewsHow to send keyboard commands to emulator?
Eai Galera, I’m trying to make a program to make an automatic combo in a fighting game (The King of Fighters 2002), I’ve tried to use libraries like pyautogui, Keyboard, ctypes and etc, but I can’t…
-
3
votes1
answer51
viewsCreate 2 zipped files with files from a folder
I’m trying to create a code that reads a directory with pdf files and creates 2 zipped files containing these pdf, in my code, I only managed to play all pdf in a single zipped file, my question is…
-
3
votes3
answers713
viewsCombination of two lists in Python
I need a code that discovers possible passwords in a universe of LLLDDD (L=letter, d=digit), I found it easier to apply the conditions separately and I arrived at two lists: lpossiveis:['ABD',…
-
3
votes1
answer142
viewsRegex is not checking the accented character, even though it is in the expression
I have the following Python regex to filter my application text input: import re good_chars_regexp = re.compile(r"^[A-Za-záéíóúÁÉÍÓÚâêîôÂÊÎÔãõÃÕçÇ00-9\,\.\-\?\"\'\’\!\“\s\;\:\“\”\–\‘\’\’\/\\]+$",…
-
3
votes2
answers639
viewsGenerate random numbers in 2d numpy array without repeating Python
Good afternoon, I’m trying to generate a 2d numpy array without repeating numbers. My code: TAMANHO = 4 tabela= np.zeros((TAMANHO, TAMANHO), dtype = int) tabela[:, 0] = np.random.randint(1, 170,…
-
3
votes2
answers475
viewsConnection error with SQL Server 2012 with Python
I am trying to connect to SQL Server 2012 using Python 3.7 and Ubuntu 20.04.1 LTS as follows: import pyodbc server = 'tcp:192.168.0.7, 1433' database = 'teste' username = 'teste' password = 'teste'…
-
3
votes2
answers119
viewsSearch an array (list list)
Write a function called busca that receives a matrix (each row of the matrix has four entries, representing the information related to name, registration, sector and phone) and do a search by…
-
3
votes1
answer79
viewsWhy does changing items from a list with multiple assignment not work when I use "index()" inline in assignment?
I can swap a and b with this code: lista = ['a', 'b', 'c'] item = 'a' # itens que quero localizar e trocar outro_item = 'b' # indice_item = lista.index(item) # obtenho a posição de ambos…
-
3
votes1
answer108
viewsWhat is the most efficient way to format code output to the user?
What is the most efficient way to format the output of my code? It is a classic exercise of the internet, but I would like to improve it. I want to leave the bars of "limit", (|) always with the…
-
3
votes2
answers54
viewshow to take duplicates from a list of dictionaries
i have that input . txt: Brasil#ouro#futebol feminino Argentina#bronze#basquete masculino Brasil#prata#futebol masculino Argentina#prata#tênis masculino Brasil#prata#volei feminino China#ouro#tênis…
-
3
votes2
answers311
viewsHow to use re.split() to pick only the words of a text, ignoring numbers and punctuation marks
I am given the following sentence:: texto = """ Em 2020 observamos, e catalogamos (com fotografias), os barcos que chegaram ao Porto! Até breve. """ for p in gerarPalavras(texto): print(p) I created…
-
3
votes2
answers97
viewsHow to filter rows where columns meet consecutive conditions in Python?
I’m trying to filter lines in which the columns comply with conditions consecutively. That is, if the row has columns with the conditions of after an L/I, the next column has a A/S, then return the…
-
3
votes1
answer648
viewsMake a histogram with a Gaussian curve in Python
It’s the first time I do a Python histogram, but I’m not getting the same Python histogram I got in Excel. Also, I wanted to put a Gaussian curve and the mean with the uncertainty of it next to the…
-
3
votes2
answers368
viewsCount occurrences of a letter in a string that repeats several times to a character limit
In this problem I have to count the number of times the letter appears 'a' in string 'a' range 1000000000000, only that I have run time error when it is a very high number like this. for example: if…
-
3
votes3
answers105
viewsFind and change specific Python dictionary
I have to perform a search inside a list with dictionaries inside, looking for the person’s specific CPF, to confirm their data, and thus change some specific dictionary item. My list is:…
-
3
votes1
answer65
viewsReplace strings with list elements
# Código list = [a for a in range(100,103)] df = pd.DataFrame({ "A":['x','y','z'], "B":[0,1,2], "C":[0,0,0] }) I need to replace column strings C by the strings of list, so that the first string of…
-
3
votes1
answer56
viewsGet the name of the Variable by which the function or class was called
I was looking at how the databases are created in Sqlalchemy and I was in doubt in the part where I create class variables and are converted to a column in the database with the name of the variable…
-
3
votes0
answers105
viewsHow to make my python server work on an external network using ngrok?
I created a server in python that runs on port 50000... Soon after that I created my client. If the two are on the same network both connect and everything is fine! But in external network I can not…
-
3
votes1
answer126
viewsFastest way to iterate over lines in python, pandas
I’m having a certain performance difficulty in the code because it’s taking too long to run. I have the following Dataframe. (Example because what I’m wearing is much bigger) orders = {'Código':…
-
3
votes3
answers179
viewsBasic Python repetition - doubt in "and" and "or"
Hello, I’m learning Python. A question arose in a repetition exercise (for). The exercise is to identify all odd numbers and at the same time multiples of 3, in the range of 0 to 500. The solution…
-
3
votes1
answer41
viewsPivoting in Pandas
Hey there, guys. I have a table in pandas and would like to turn the values in the column DE_ANALITO into columns whose values would be what is in the column DE_RESULTADO.…
-
3
votes2
answers58
viewsHow does the numpy Prod method work?
I’ve always used the method np.prod as a production operator. So if I want to know the factorial of 5, for example, I simply do: import numpy as np np.prod([5,4,3,2,1]) 120 It turns out I was…
-
3
votes1
answer85
viewsReplace string_concat() with equivalent
I am a beginner in Python and accepted to participate in a more or less old project, which was using Python 2.7 so far. At the beginning of the year, this version was deprecated and now I can’t…
-
3
votes1
answer52
viewsApply row-to-row formula within a table in R
I have a table where I need to apply a row-to-row formula to multiple columns, and the formula is: row value - mean(all column values) / standard deviation(all column values) is a normalization of…
-
3
votes2
answers55
viewsHow to save a dictionary to two independent objects in Python?
Consider the following dictionaries: dic1 = {'k1':'Ford','k2':'GM','k3':'Dodge'} dic2 = {'k4':'Audi','k5':'Mercedes','k6':'VW'} dic3 = {'k7':'Fiat','k8':'Mazda'} The goal is to get two new…
-
3
votes2
answers172
viewsSelect Dataframe lines based on list of values for a column
I have a Dataframe with more than 5 thousand lines and more than 20 columns. I want to select only a few rows, second column match criteria with specific values SELECT * FROM dataframe WHERE…