List range is being taken as tuple rather than integers - python

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.

Related

add select values in a tuple with python

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)

How to get index position of values in python

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))

Python: How to convert a long number into string?

I was trying to transform this long number data inside tuple into a string so I can preserved its value when I send it to JSON (The file with this data inside is named b.json)
"ecc": [
79849177969901016848164770310957289409900866592060952979899491148125256206126,
80012691714024297247210932953164632591330351085279802419411702853992977368435
]
So I try to run this command in Python
with open('b.json', 'r') as editfile:
data2 = json.load(editfile)
tmp = data2["ecc"]
tmp = [tuple(str(x) for x in tup) for tup in tmp]
data2["ecc"] = tmp
But I got this result
Traceback (most recent call last):
File "temp-hum-log.py", line 94, in <module>
tmp = [tuple(str(x) for x in tup) for tup in tmp]
TypeError: 'long' object is not iterable
So what should I do to convert this long number into string?
You went one level to deep, it's trying to iterate over this long number like it would iterate over list or string.
Try this:
with open('b.json', 'r') as editfile:
data2 = json.load(editfile)
tmp = data2["ecc"]
tmp = [str(number) for number in tmp]
data2["ecc"] = tmp
Also there is a special Decimal class for storing long number as string and you can run mathematic operations on them.

Why might python be interpreting my dictionary as a list?

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

strip ' from all members in a list

Ok, so I converted each line in a text file into a member of a list by doing the following: chkseq=[line.strip() for line in open("sequence.txt")] So when I print chkseq I get this: ['3','3'] What I would like is for it to instead look like this: [3,3] I know this is possible, I'm just unsure of how! I need them to be intergers, not strings. So if all else fails, that is my main goal in this: create a list from a .txt file whose members are intergers (which would be all the .txt file contained). Thanks!! -OSFTW
It looks like you want to interpret the strings as integers. Use int to do this:
chkseq = [int(line) for line in open("sequence.txt")]
It can also be written using map instead of a list comprehension:
chkseq = map(int, open("sequence.txt"))
iterate over the elements of your list and print them out with your preferred formatting rather than relying on the default formatting when printing the whole list at once.
Say your array is called input, and you want to store the value in an array called chkseq, your code would be:
chkseq = [int(i) for i in input]
Or, if you wanted to do everything all in one line:
chkseq = [int(i.strip()) for i in open("sequence.txt")]
Passing a string to the int constructor will attempt to turn it into a int.
>>> int('3')
3
>>> int('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

Categories