does anyone know why that error comes out when trying to add four positions in a variable?
I have tried with only one position and it works for me, but if I try to add more it gives me an error:
My error:
Traceback (most recent call last):
File "\script.py", line 165, in <module>
Ad100()
File "\script.py", line 142, in Ad100
baseAd100.extend(row[0,2,3,4])
TypeError: tuple indices must be integers or slices, not tuple
My code:
def Ad100():
for rows in pcorte: ##pcorte es el resultado de una consulta.
print(rows)
baseAd100 = []
for row in pcorte:
## llenado.append(row[0]) this way works for me in another function with only the first position
baseAd100.extend(row[0,2,3,4]) ##in this way it generates an error
print(baseAd100)
My data:
('220002393681', '0171', '823', 'S', 1008, '25175', 997, 547)
List/tuple indexing doesn't work that with with comma-separated values. You either get one item (row[1]) or a slice of items, e.g. row[1:4] gets items 1 up to but not including 4. See slice() for more details.
There is a method to get non-contiguous indices however:
from operator import itemgetter
baseAd100 = []
row = ('220002393681', '0171', '823', 'S', 1008, '25175', 997, 547)
baseAd100.extend(itemgetter(0,2,3,4)(row))
print(baseAd100)
Output:
['220002393681', '823', 'S', 1008]
itemgetter(0,2,3,4) generates a function that will extract the specified indices
from the argument, then it is passed the row.
thanks #Pranav Hosagadi guide me with your comment, it's not the best, but that's how my code looks
def Ad100():
baseAd100 = []
for row in val:
baseAd100.append(str(row[0])+"," + str(row[2:4]))
print(baseAd100)
Related
I am a beginner and trying to solve a problem.
- Find the highest number in a list (without using max() function) with below instructions
create a text file which has a list
create a function to identify highest value in a list
in a separate program, read the text file created in step# 1 and using function from step #2 above find the highest value in the list given in text file
Solution Tried:
I created a text file with a list in a folder [23, -1, 5, 4]
created a function (funcion_list.py) to find the highest value in list
def max_item(list):
maximum = 0
for value in list:
if value > maximum:
maximum = value
return maximum
in my playground.py program, I imported the function max_item(list), read the list from the text file and passed it as an argument in the function to find the highest number in the list
from function_list import max_item
new_list = []
with open("file1.txt", "r") as f:
for line in f:
print(line.rstrip("\n"))
new_list.append((line))
print(max_item(new_list))
Output:
I am able to read the appended file but I am getting below error instead of getting highest value printed.
Traceback (most recent call last):
File "playground.py", line 13, in <module>
print(max_item(new_list))
^^^^^^^^^^^^^^^^^^
File "function_list.py", line 4, in max_item
if value > maximum:
^^^^^^^^^^^^^^^
TypeError: '>' not supported between instances of 'str' and 'int'
Could you please help in pointing what wrong am I doing?
open will read everything as a string. You need to convert it to an int before adding it to the list.
Change this line
new_list.append((line))
to
new_list.append((int(line)))
I have the following list of suubjects and grades I have named "gradebook"
gradebook list
I am attempting to remove the value 85 from the sublist [poetry, 85]
sublist
I can remove the sublist itself with the following syntax
gradebook.remove(["poetry", 85])
I can't seem to remove the 85
I have tried to use the following syntax
gradebook.remove([85])
but I get the following error
> Traceback (most recent call last): File "script.py", line 15, in
> <module>
> gradebook.remove([85]) ValueError: list.remove(x): x not in list
I have also tried to use the following
gradebook.remove([2][1])
Instead I get the following error
Traceback (most recent call last): File "script.py", line 15, in
gradebook.remove(2) IndexError: list index out of range
I don't know if it is possible to, but how can I remove that item (85) in the sublist?
When dealing with multi-dimensional data you need to navigate to the item you want to operate on before submethods will work as you expect. Your data is a list of lists, so you need to let the program know you want to operate on a specific list within your data. Your data is below.
gradebook = [[“physics”, 98], [“calculus”, 97], [“poetry”, 85], [“history”, 88]]
Navigate to the item of index 2 so the returned value is the list ["poetry", 85]. Then you can operate on this list individually by calling the .remove(85) method.
# Define gradeboook
gradebook = [[“physics”, 98], [“calculus”, 97], [“poetry”, 85], [“history”, 88]]
# Get the index of your list
index = gradebook.index(["poetry", 85])
# Navigate and remove 85
gradebook[index].remove(85)
You can also do the last two steps with one line:
gradebook[gradebook.index(["poetry", 85])].remove(85)
This works because the item returned when you call gradebook[gradebook.index(["poetry", 85])] is the list ["poetry", 85] itself. Once you call it in this way you can modify it with remove(), as you please.
So index starts at 0 for lists so you could just do del gradebook[1]
I have a scenario , where I am trying to get index position of value
My code :
a_set = {22,56,26}
print(a_set[56])
Getting below error
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: 'set' object is not subscriptable
Expected output :
1 -> This the position of 56 from set
The error is explaining a lot here: sets in Python are not subscriptable.
They dont have order relation.
According to your code example, you are trying to ask weather a value exists in the set, right?
In Python you can do it with in operator:
>> print(36 in a_set)
True
or
if (36 in a_set):
my_function()
Sets are by definition completely unordered and unindexed, you cannot get the information with an index directly as that is not what they were made for. As a workaround, you can simply convert the set to a list that is both indexed and ordered.
a_set = {22,56,26}
print(list(a_set)[3]) # converts the set into and displays it's third entry.
To solve your problem, you can use .index() on the new list such as this:
a_set = {1,2,3}
print(list(a_set).index(1))
I'm writing a program to sort through csv files. It is supposed to pull lines from the files and based on whether a "donor" is already in the dictionary, either add the "donor" to the dictionary or append the information in the line to the old value. I'm getting the error statement:
error statement: File "C:/Users/riley/Desktop/Python Files/MYLATEST1.py", line 27, in
donors[donor] = [[data]]
builtins.TypeError: list indices must be integers or slices, not tuple
I'm new to python, but it seems as if python is interpreting my dictionary as a list. Is that what's going on? If so, why? Thanks for any help!
def createDonorDirect():
listoffiles = glob.glob('C:/Users/riley/Desktop/mydata//*.csv') #glob allows you to create a list of files/folders that match wildcard expression in this case all the csv files in the directory
# Create donors directory
donors = {}
for filename in listoffiles:
with open(filename) as file:
for line in file:
# line processing stuff
data = line.split(',')
donor = ''.join(data[3,5,7])
# populate data structure
if donor in donors:
donors[donor].append(data)
else:
donors[donor] = [[data]]
The reason for the error is you are assigning donor to tuple value as key, which is wrong here since tuple content multiple values.
sample problem regeneration with code:-
>>> data=['HI','Hello','How','are','you','my','name','is']
>>> donor = ''.join(data[3,5,7])
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
donor = ''.join(data[3,5,7])
**TypeError: list indices must be integers or slices, not tuple**
>>>
second simplified code:-
>>> data[3,5,7]
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
data[3,5,7]
TypeError: list indices must be integers or slices, not tuple
Tuple declaration can be little confusing sometimes.
For example: SOME_CONSTANT = 1, is same as SOME_CONSTANT = (1, ) . Both are a tuple.
On the other hand, SOME_CONSTANT = (1) will be same as SOME_CONSTANT = 1. Both are an integer.
In your case you just need to change:
donor = ''.join(data[3,5,7])
to
donor = ''.join(data[3] + data[5] + data[7])
Example:
data=['A','B','C','D','E','F','G','H']
print ''.join(data[3] + data[5] + data[7])
DFH
I am trying to fetch elements from a list as per following code:
"data" is a string containing some data from which i am taking out values of start and end offset.
I am then multiplying the start and end Offset by 4 to calculate start,endOffsetAsPerPage.
startOffset = data.split(",,")[1].split(":")[1];
endOffset = data.split(",,")[2].split(":")[1];
startOffsetAsPerPage = int(startOffset)*4;
endOffsetAsPerPage = int (endOffset)*4;
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)];
While executing, i am facing following error:
Traceback (most recent call last):
File "CassandraDataAPIResultValidator.py", line 55, in <module>
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)];
TypeError: list indices must be integers, not tuple
Can you please help here.
Thanks in advance.
You are using a comma:
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)]
# ^
A comma there makes it a tuple, not a slice.
Use a colon instead:
FilteredData = CassandraData[int(startOffsetAsPerPage):int(endOffsetAsPerPage)]
# ^
Note that Python doesn't need to use semicolons at the ends of lines.