strip ' from all members in a list - python

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'

Related

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

Don't understand the cause of this AttributeError

What's wrong with that code? When I run it tells me this:
Traceback (most recent call last):
line 24, in <module>
people.append(Dict)
AttributeError: 'str' object has no attribute 'append'
My code:
live = 1
while live == 1:
#reading Database
dataRead = open ("db.txt","r")
if dataRead.read() != " ":
dataRead.close()
people = open ('db.txt','r').read()
do = input ('What Do You Want ? (Search , add) :\n')
#add people
if do == 'add':
#Get The New Data
n_Name = input ('enter the new name:\n')
n_age = input ('enter the new age:\n')
#new Dict
Dict = {'Name:':n_Name,'age':n_age}
people.append(Dict)
#adding people to file
dataWrite = open ("db.txt","w")
dataWrite.write(str(people))
dataWrite.close()
live = 0
The problem is, on line 24, you try to append a dictionary to a string. When you read the db file, it read it as a string. Also the code is really messy and there are a lot better ways to do it. But that's besides the point, the append() method is for lists and the variable "people" is a string, according to your error output.
It says that people is str then it doesn't have an append method. You should just concatenate strings to get them together.
Do:
people += '<append string>'
Have in mind you are trying to append a dictionary to a string. This will throw TypeError cause those type of elements can't be concatenated that way. You should do first: str(dict) to concatenate them.
You're also using a reserved word like dict as a variable. Change it to my_dict or other allowed name.

Reading in string of nested JSON lists and dictionaries with Python

I am having trouble reading data in python. A sample of one of the rows is:
foo_brackets='{"KEY2":[{"KEY2a":[{"KEY2a1":"4","KEY2a2":"5"},{"KEY2a1":"6","KEY2a2":"7"}],"KEY2b":"8"}],"KEY3":"9"}'
When I load with json, the value for KEY2 is read in as a list, because of the brackets, which then prevents me from getting at my desired result, which is the value of KEY2b:
>>> import json
>>> foo_brackets_json=json.loads(foo_brackets)
>>> foo_brackets_json['KEY2']['KEY2b']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
I could just try to remove the brackets, but there actually is a value that should be a list, KEY2a. You can see this if I strip out all the brackets and try to convert to JSON:
>>> foo_no_brackets='{"KEY2":{"KEY2a":{"KEY2a1":"4","KEY2a2":"5"},{"KEY2a1":"6","KEY2a2":"7"},"KEY2b":"8"},"KEY3":"9"}'
>>> json.loads(foo_no_brackets)
# Traceback omitted since it's just the python error
ValueError: Expecting property name: line 1 column 45 (char 45)
foo_brackets does appear to be valid JSON (I tested here, with the quotes removed) and got the following:
{
"KEY2":[
{
"KEY2a":[
{
"KEY2a1":"4",
"KEY2a2":"5"
},
{
"KEY2a1":"6",
"KEY2a2":"7"
}
],
"KEY2b":"8"
}
],
"KEY3":"9"
}
Question:
Is there a way for me to read objects like foo_brackets so that I can call foo_brackets_json['KEY2']['KEY2b']?
foo_brackets_json['KEY2'] references a list, here with one element.
You'll have to use integer indices to reference the dictionaries contained in that list:
foo_brackets_json['KEY2'][0]['KEY2b']
Don't try to remove the brackets; there could be 0 or more nested dictionaries here. You'll have to determine what should happen in those cases where you don't have just 1 nested dictionary.
The above hardcoded reference assumes there is always at least one such a dictionary in the list, and doesn't care if there are more than one.
You could use looping to handle the 0 or more case:
for nested in foo_brackets_json['KEY2']:
print(nested['KEY2b'])
Now you are handling each nested dictionary, one by one. This'll work for the empty list case, and if there is more than one.
You could make having 0 or more than one an error:
if len(foo_brackets_json['KEY2']) != 1:
raise ValueError('Unexpected number of results')
etc. etc. It all depends on your actual use-case.

List range is being taken as tuple rather than integers

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.

convert float values in dictionary into two decimal places

Note, using Python 2.4. Here is a dictionary I have called d_ourbook:
{'130405C00465000': [[8.6999999999999993, 8.9000000000000004, 0.50749999999999995, 32.810000000000002, -141.1575]]}
The value is a list of floats. I am trying to make a function that displays the same dictionary, but with values limited to two floating points.
I made a floating point --> 2decimal string function called two(floatnum):
def two(floatnum):
return '%.2f' %(floatnum)
My function to loop or zip through the dictionary and convert all the values to two(value) have been a nightmare and returns float argument required:
Traceback (most recent call last):
File "esecombo.py", line 496, in ?
print ' -- dt: ', dt(d_ourbook)
File "esecombo.py", line 23, in dt
new_d_name = dict(zip(d_name.keys(), [two(value)for value in d_name.values()]))
File "esecombo.py", line 10, in two
return '%.2f' %(floatnum)
TypeError: float argument required
Any help would be a lifesaver.
Assuming that d_name is the dictionary you provided, then d_name.values() is a list of lists of lists of floats. So value is a list of lists of floats and you cannot hand that to two() without an error.
Even if you get that resolved the zip returns a number of tuples base on the shortest argument.
So that:
new_d_name = dict(zip(d_name.keys(),
[two(value) for value in (d_name.values()[0][0])]))
results in {'130405C00465000': '8.70'}
This assumes that all values are of the single item list in list type as in the example, in that case you probably could use:
new_d_name = dict(zip(d_name.keys(),
[[two(value) for value in (d_name.values()[0][0])]]))
to get:
{'130405C00465000': ['8.70', '8.90', '0.51', '32.81', '-141.16']}

Categories