I have this piece of code:
for keys in self.keys:
if has_classes := self.class_checker(keys[0]):
print(type(keys[0])) -> #just for demonstrating that it is actual list
keys[0] = [x for x in keys[0] if 'class="' not in x]
for classes in has_classes:
keys[0].append(f'class="{classes}"')
I want to change the list by using list comprehension and it is showing this error:
<class 'list'>
Traceback (most recent call last):
File "C:\Users\USER\OneDrive\Desktop\XPATH\base\main.py", line 300, in <module>
XPanther('<h1 class="Uo8X3b OhScic zsYMMe">Lidhjet e qasshmërisë</h1>', 'C:\\Users\\USER\\OneDrive\\Desktop\\XPATH\\xpath_test_case.txt').capture()
File "C:\Users\USER\OneDrive\Desktop\XPATH\base\main.py", line 100, in capture
keys[0] = [x for x in keys[0] if 'class="' not in x]
~~~~^^^
TypeError: 'tuple' object does not support item assignment
As you can see on the first line of the error, it is printing the type of keys[0] as a list (which I also know is a list but anyways), and then it suddenly becomes a tuple ?
I'm very confused, please someone help me!
As #bereal has mentioned (and others..) in the comments of my post, the actual case for this problem is that I tried to change the contents of a list,which that list happens to be inside a tuple, which is immutable in itself, so i can't change it's values at all. The obvious solution would be to first transform the tuple into a list,then back again as a tuple if you want.
Related
I have a table of data in a txt file.
I bring it into Python with:
a1_file=open(file_path,'r')
then I go to the second line to skip the headers:
a1_file.readline()
line_string=a1_file.readline()
Being a comma separated function I want to obtain a list where the position of the first 5 commas is stored. To this purspose I am trying to use this function:
def commas_in_line(table_row):
commas=[]
while len(commas) <5:
if len(commas)==0:
i=0
else:
i=commas[-1]+1
k=table_row.find(',',i)
commas=commas.append(k)
return commas
I call the function with:
commas_in_line(line_string)
The code reports this error:
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
commas_in_line(line_string)
File "C:/1WritingPrograms.py", line 11, in commas_in_line
while len(commas) <5:
TypeError: object of type 'NoneType' has no len()
with
>>> line_string
'30/04/2020,30,4,2020,122,0,Afghanistan,AF,AFG,37172386,Asia\n'
I tried substituting in the function:
commas=commas.append(k)
with:
commas=commas+[k]
and it works, but how can I use the append method? Why does it fail?
Essentially .append() does not return the new array. .append() is sort of like an inplace function, where the value is appended into the array. So you do not have to return anything. When you say commas=commas.append(k), a new entity is returned, which is NoneType. Please just leave it as commas.append(k)
You add values to a python list with:
commas.append(k)
You use the = operator to define a list, not to alter one. For instance, for
commas = ['a', 'b', 'c']
commas.append('d')
commas will now be (a, b, c, d).
There is more about python lists here https://www.w3schools.com/python/python_lists.asp
First post ever :)
I know that the if statement returns a Boolean value. But I am not using it to iterate a list, I'm using x. I just want all other variables (type = IntVar) to be set to 0 except for i which has to remain 1. Thanks in advance, my first ever time here...
def clear():
variables=[var, var0, var1, var2, var3, var4,var5,var6, var7, var8]
for i in variables:
if i.get() == 1:
x = variables.index(i)
for y in variables in range(0,x-1) and range(x,9):
y.set(0)
My original code is 500 lines long so not ideal to post it full here.
Full traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Thomas Jence\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "G:\Mrs. Odewale\Computing coursework\options.py", line 187, in clear9
for y in variables in range(0,x-1) and range(x,9):
TypeError: 'bool' object is not iterable
for y in variables in range(0,x-1) and range(x,9):
is interpreted as (split up with parentheses and by line to make groupings clear):
for y in (
variables in (
range(0, x-1) and range(x,9)
)
):
The innermost parentheses then determine if range(0, x-1) is empty or not, and use it if it's not, and use range(x,9) if it is. The next layer then tests if variables is in the "winning" range. Then you effectively do:
for y in False:
because variables is a list, so it's definitely not in any range.
I don't know what you're trying to do, but you need to reconsider that line.
Not familiar with python, but as a standard coding practice you never want to change values in an array while you are iterating through them.
Instead create a new array, which has same values as the existing array. iterate the old array while setting values of the new array, and then after the loop, set the your array to the new values of the new array.
When it comes to wrapping a tkinter object (or multiple) in a list, there seems to be a descrepency between using the square bracket operators [] vs. the list() constructor:
In 1:
>>> import tkinter as tk
>>> list(tk.Entry())
Out 1:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1486, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: must be str, not int
In 2:
>>> [tk.Entry()]
Out 2:
[<tkinter.Entry object .!entry2>]
This is quite confusing considering that type(tk.Entry()) yields <class 'tkinter.Entry'> as expected, not int. Thanks in advance.
As you have been told in the comments, list(x) and [x] are not the same.
The nature of the reported error is more interesting. When you attempt to convert an Entry to a list, list() calls the method __getitem__ from the Entry. For whatever reason, this method is implemented as an alias to Entry.cget():
x = tk.Entry()
x.cget == x.__getitem__
#True
So, list(x) calls x.__getitem__(0) to obtain the first element of the anticipated iterable. This, in turn, calls x.cget(0); this, in turn, attempts to obtain the value of the widget configuration option '-' + 0. The latter operation is invalid and results in the error message that you observed.
I am trying to add some keys to my dictionary after testing if they are already existing keys. But I seem not to be able to do the test, every time I get the TypeError "argument of type 'type' not iterable.
This is basically my code:
dictionary = dict
sentence = "What the heck"
for word in sentence:
if not word in dictionary:
dictionary.update({word:1})
I also tried if not dictionary.has_key(word) but it didn't work either so I am really confused.
Your error is here:
dictionary = dict
That creates a reference to the type object dict, not an empty dictionary. That type object is indeed not iterable:
>>> 'foo' in dict
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'type' is not iterable
Use {} instead:
dictionary = {}
You could also have used dict() (calling the type to produce an empty dictionary), but the {} syntax is preferred (it is faster and easier to scan for visually in a piece of code).
You also have an issue with your for loop; looping over as string gives you the individual letters, not words:
>>> for word in "the quick":
... print(word)
...
t
h
e
q
u
i
c
k
If you wanted words, you could split on whitespace with str.split():
for word in sentence.split():
I've spent quite some time searching to see if there was a similar issue. Unfortunately, I couldn't just comment on the previously asked question to see why my attempt was not working.
On this site there exists a question where a person wants to sort a list, according to closest numbers to a specific value.
his example:not verbatim copying his example but putting a working solution
list_x = [1,2,5,11]
list_x.sort(key = lambda x: abs(x-4))
which will return the list sorted by values closest to 4 (5,2,1,11)
However, when trying to sort a much larger list by values closest to zero this is happening to me:
listA.sort(key = lambda x: abs(x))
Traceback (most recent call last):
File "<pyshell#382>", line 1, in <module>
listA.sort(key = lambda x: abs(x))
File "<pyshell#382>", line 1, in <lambda>
listA.sort(key = lambda x: abs(x))
TypeError: bad operand type for abs(): 'str'
What exactly am I doing incorrectly thats preventing the list from being sorted by absolute values?
This is input data for what makes listA
for i in decrange(0, 13, i):
code = (func(seq, float(i)))
codes = '%.3f' % code
listA.append(float(codes))
listB.append(str(codes))
listA.sort(key = lambda k: abs(k))
x = listA[0]
answer = listB.index(x) * float(.01)
The error you're getting seems fairly self-explanatory:
TypeError: bad operand type for abs(): 'str'
It looks like somewhere in your list you have a string value instead of a numeric value. This will work (assuming integer values):
listA.sort(key = lambda x: abs(int(x)))
...but it would be better to figure out why your list has strings in it and fix that instead.