Category Archives: Python

TypeError: list indices must be integers or slices, not str

Error:

TypeError: list indices must be integers or slices, not str

error code block:

AA is a set of list and dict data

The function insert receives two parameters, * args, * * kwargs

I hope to pass the list AA to * args

But in the execution of the program, a title display error was reported

first of all, the basic concepts of * args and * kwargs:

For * args and * * kwargs, we can call them parameter groups in functions, but they are different

1: * functions of args: – – – receive n position parameters and convert them into tuple form

2: The function of * * kwargs is to receive n keyword parameters and convert them into dict form

3: The location parameter must precede the keyword parameter, that is, (* args, * * kwargs)
 

problem analysis:

A * sign before the parameter AA indicates that it is an assembled tuple, otherwise Python will think AA is a positional parameter

So the program can run as expected

Python TypeError: ‘int’ object is not iterable

Use a loop to print out each name in the list in turnHello, xxx!

——————————————————–

L = [‘Bart’, ‘Lisa’, ‘Adam’]
x = len(L)

for i in range(x):

print(‘Hello,’, L[i])

——————————————————–

Here, if you use for i in x directly, the compiler reports an error.TypeError: ‘int’ object is not iterable:

Traceback(mostrecentcalllast):
File”main.py”,line5,in<module>
foriinx:
TypeError:’int’objectisnotiterable

The reason for this problem is that you cannot iterate directly with int, but must use the range method, i.e. range(x).

[Solved] Python TypeError: ‘int’ object is not callable

TypeError:’int’ object is not callable

The reason for this error is simple

Look at the following program:

1  def loss(a,b):
 2      return a- b
 3  
4 loss = 0
 5 loss = loss(5,2)+1

Error positioning:

loss = loss(5,2)+1
TypeError:’int’ object is not callable

 

the reason:

Function name loss

Variable name loss

coincide! ! !

 

TypeError: Image data of dtype object cannot be converted to float

The source code is as follows:

import os
import cv2
import random
import numpy as np
from tqdm import tqdm

from matplotlib import pyplot as plt

# View two pictures
img_path1 = "cat2.jpg"
img_check1 = cv2.imread(img_path1, cv2.IMREAD_GRAYSCALE)
img_path2 = "cat3.jpg"
img_check2 = cv2.imread(img_path2, cv2.IMREAD_GRAYSCALE)
# Show picture
fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(13,7))
axes[0].imshow(img_check1,'gray')
axes[1].imshow(img_check2,'gray')
plt.show()

When the program is running, it always reports an error in the code marked with red. It takes a long time to find that it has made a very stupid error: the path is wrong (at the same time, the path contains Chinese). Although the path is wrong, it always reports another error, so it is difficult to find this problem

So when you have the same error, you can check whether the path contains a Chinese name or the path is wrong. Solutions for reference only, if there is a better solution, welcome to leave a message

Problems and solutions of typeerror: ‘generator’ object is not subscriptable in openpyxl

Today, a package called openpyxl was used to parse the excel data to build the driver data framework.
Then the TypeError:’generator’ object is not subscriptable bug

appeared . The specific problem in the above picture appeared in print(pe.getCellOfObject(sheet, rowNo=1 , colsNo=1)) After
checking the code for a long time, there is no problem. Finally, I asked Du Niang to find out that it was the version number.
Since I installed the version of openpyxl3.0.0, I just need to replace the 2.3.3 or 2.3.5 version.

Solution: 

It is recommended to change the version of openpyxl to 2.3.3 or 2.3.5

 

Python TypeError: file must have ‘read’ and ‘readline’ attributes

Python Error: TypeError: file must have ‘read’ and ‘readline’ attributes

Error when running serialization (pickle) related functions: TypeError: file must have ‘read’ and ‘readline’ attributes

Code above.

>>> fp = open("a.txt","r+")
>>> import pickle
>>> pickle.load("fp")#error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: file must have 'read' and 'readline' attributes

Cause analysis: the parameter in the load () method is wrongly written. If there is one more “” and it can be removed

Solution:

Change to the following method

>>> fp = open("a.txt","rb+")
>>> import pickle
>>> pickle.load(fp)#Serialized Print Results
['apple', 'mango', 'carrot']

Solutions to typeerror: expected string or bytes like object error

During the previous development project, data migration has been carried out many times, but after a period of time, when the data migration was reopened, a “TypeError: expected string or bytes-like object” type error occurred. The reason may be the inconsistency of the code in the program caused by the change of the database version, and the coding conflict caused by the existence of records during the previous migration. . . .

Of course, this is just my guess. As a Django novice, I am not quite clear about its internal structure. Hope to see the big guys can give pointers. Not much to say, the solution is as follows: I use xadmin background management,

So in the migrations directory corresponding to xadmi, delete the file starting with 0003_auto, and then re-migrate the data. In case it still doesn’t work, I personally think that you can delete all the files except _init_.py. Because I deleted it on another project, it will not affect the operation of the project, just re-migrate.

 

The solution of typeerror: expected string or buffer

Error type: TypeError: expected string or buffer

Specific error explanation: This is because the returned variable is not a character type, which causes this error

The specific solution: add an if statement before the specific program segment to determine whether the program returns in a legal format, and if it is, continue to run the program.


[+] Because the return result of readlines is a sequence, but the 8th line should accept characters. So it leads to an error. You should use a for loop to make it into a character and then use regular matching.

 

Python Pandas TypeError: Empty ‘DataFrame’: no numeric data to plot

Tushare returns the dataframe format of panda, but an error occurs when executing the following code: typeerror: empty ‘dataframe’: no numeric data to plot

import tushare as ts

df_all = ts.realtime_boxoffice()
df_box_office = df['BoxOffice']
df_box_office.index = df['Irank']
df_box_office.plot(kind='bar')

Repeatedly output DF [‘boxoffice ‘] to confirm that it has value. I can’t figure out why it will report “empty”, and Baidu has no result

I thought there was a bug in the combination of tusahre and pandas. When I was ready to give up, I saw “numeric” in the error report. Does it mean that DF [‘boxoffice ‘] is a string type, not a numeric type, which leads to the error report

See the usage of “astype ()” in the official documents of panda, and change the code to the following successful drawing (in addition, use “ PD. To_ Numeric () “is OK, but I have to go back to panda from tushare. I feel that the code doesn’t look so smooth

import tushare as ts

df_all = ts.realtime_boxoffice()
df_box_office = df['BoxOffice'].astype(float)
df_box_office.index = df['Irank']
df_box_office.plot(kind='bar')