Converting list to string then integer - python

I have a list with 1550500 numbers, and all of them with quotes.
Example: list('100', '150', '200', '250') etc...
I need to sum all the numbers, but before that I need to convert it to INT.
List Name: trip_list
My code:
mean_tripstr = str(trip_list)
mean_trip = [int(x) for x in mean_tripstr]
print(type(mean_trip))
Error message:
Traceback (most recent call last):
File "projeto1.py", line 235, in <module>
mean_trip = [int(x) for x in mean_tripstr]
File "projeto1.py", line 235, in <listcomp>
mean_trip = [int(x) for x in mean_tripstr]
ValueError: invalid literal for int() with base 10: '['
What am I doing wrong? I am new to coding...

Python has a map function, this takes a function and an iterable. There is also the sum function, which returns the sum of an iterable.
You can use this:
sum(map(int(trip_list))
Note that the map function does not return a list, it returns a generator. To convert it to a list, use
list(sum(map(int, trip_list)))
(this may take a while as it requires iterating over the entire list, and yours is quite long).
The error with your code is converting your list to a string, that is,
>>> my_list = ["5", "6"]
>>> my_list_str = str(my_list)
>>> my_list_str
"['5', '6']"
>>> type(my_list_str)
<class 'str'>
>>> type(my_list)
<class 'list'>
So when you try to iterate over the string, the first x is [ which is not a number (thus the exception).
As a sidenote, using list(map(int, a_list)) is faster than [int(i) for i in a_list]
>>> c1 = "list(map(int, a_list))"
>>> c2 = "[int(i) for i in a_list]"
>>> s = "a_list = [str(i) for i in range(1000)]"
>>> import timeit
>>> timeit.timeit(c1, setup=s, number=10000)
1.9165708439999918
>>> >>> timeit.timeit(c2, setup=s, number=10000)
2.470973639999997

You have to convert each element to int:
mean_tripstr = map(str,trip_list)
mean_trip = list(map(int,mean_tripstr))
The code above uses a generator, what is more efficient in cases when you just have to iterate in a list. The last line convert to a list again properly.
But, as you said, if you already have a list of strings, you can just do:
mean_trip = list(map(int,trip_list))
If you know numpy, you can do too:
import numpy as np
trip_list = np.array(trip_list)
mean_trip = trip_list.astype(np.int)

Related

Use split for specific elements of multidimensional list

I have the following list (the actual file is much larger and complex)
a = [[['3x5'], ['ff']], [['4x10'], ['gg']]]
I would like to use the split functionality for the first element in the list and get the value in which appears after "x". The final results should be 5 and 10 in this case. I tried to use split in this format
for line in a:
print str(line[0]).split("x")[1]
but the output is
5']
10']
I know I can easily manipulate the output to get 5 and 10 but what is the correct way of using split in this case?
And I am interested in using split for specific element of a list (first elements in this case).
You need to dive one level deeper, and dont use str() on the list.
>>> a = [[['3x5'], ['ff']], [['4x10'], ['gg']]]
>>> for y in a:
... if 'x' in y[0][0]:
... print y[0][0].split('x')[-1]
5
10
You shouldn't the list to a string object, however, you can do it use:
>>> [i[0][0].split('x')[1] for i in a]
['5', '10']
I think you also want to convert the output to int object, then you can simply add an int() like below:
>>> [int(i[0][0].split('x')[1]) for i in a]
[5, 10]
However, if you don't need save the output into a list, but print it out instead, you can just use the same code, but write another version:
a = [[['3x5'], ['ff']], [['4x10'], ['gg']]]
for i in a:
print(i[0][0].split('x')[1])
Output:
5
10
Remember that my code will failed (raise IndexError: list index out of range) when a is... For example [[['3x5'], ['ff']], [['kk'], ['gg']]] (the first element in one of the sublists isn't in format like '3x5').
However, a simple if can fix this:
>>> a = [[['3x5'], ['ff']], [['kk'], ['gg']]]
>>> [int(i[0][0].split('x')[1]) for i in a]
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 1, in <listcomp>
IndexError: list index out of range
>>> [int(i[0][0].split('x')[1]) for i in a if 'x' in i[0][0]]
[5]
Or even better, use RegEx to check, which can avoid something like a = [[['3x5'], ['ff']], [['xxxxxxx'], ['gg']]]:
>>> import re
>>> a = [[['3x5'], ['ff']], [['xxxxxxx'], ['gg']]]
>>> [int(i[0][0].split('x')[1]) for i in a if re.search(r'\d+x\d+', i[0][0])]
[5]
Another way, if you don't want import re:
>>> [int(i[0][0].split('x')[1]) for i in a
... if all(j.isdigit() for j in i[0][0].split('x'))]
[5]

TypeError: 'list' object cannot be interpreted as an integer

The playSound function is taking a list of integers, and is going to play a sound for every different number. So if one of the numbers in the list is 1, 1 has a designated sound that it will play.
def userNum(iterations):
myList = []
for i in range(iterations):
a = int(input("Enter a number for sound: "))
myList.append(a)
return myList
print(myList)
def playSound(myList):
for i in range(myList):
if i == 1:
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
I am getting this error:
TypeError: 'list' object cannot be interpreted as an integer
I have tried a few ways to convert the list to integers. I am not too sure what I need to change. I am sure that there is a more efficient way of doing this. Any help would be very greatly appreciated.
Error messages usually mean precisely what they say. So they must be read very carefully. When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is. It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.
So the question is: why does the interpreter seem to want to interpret your list as an integer? The answer is that you are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in myList instead.
For me i was getting this error because i needed to put the arrays in paratheses. The error is a bit tricky in this case...
ie. concatenate((a, b)) is right
not concatenate(a, b)
hope that helps.
The error is from this:
def playSound(myList):
for i in range(myList): # <= myList is a list, not an integer
You cannot pass a list to range which expects an integer. Most likely, you meant to do:
def playSound(myList):
for list_item in myList:
OR
def playSound(myList):
for i in range(len(myList)):
OR
def playSound(myList):
for i, list_item in enumerate(myList):
range is expecting an integer argument, from which it will build a range of integers:
>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
Moreover, giving it a list will raise a TypeError because range will not know how to handle it:
>>> range([1, 2, 3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object cannot be interpreted as an integer
>>>
If you want to access the items in myList, loop over the list directly:
for i in myList:
...
Demo:
>>> myList = [1, 2, 3]
>>> for i in myList:
... print(i)
...
1
2
3
>>>
remove the range.
for i in myList
range takes in an integer. you want for each element in the list.
You should do this instead:
for i in myList:
# etc.
That is, remove the range() part. The range() function is used to generate a sequence of numbers, and it receives as parameters the limits to generate the range, it won't work to pass a list as parameter. For iterating over the list, just write the loop as shown above.
since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.
use this
for i in range(len(myList)):
with this, we get the singular integer value which can be used easily
In playSound(), instead of
for i in range(myList):
try
for i in myList:
This will iterate over the contents of myList, which I believe is what you want. range(myList) doesn't make any sense.
def userNum(iterations):
myList = []
for i in range(iterations):
a = int(input("Enter a number for sound: "))
myList.append(a)
print(myList) # print before return
return myList # return outside of loop
def playSound(myList):
for i in range(len(myList)): # range takes int not list
if i == 1:
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
n=input().split()
ar=[]
for i in n:
if i not in ar:
ar.append(i)
print(*ar)
We usually pass string as a integer... for that we have to type "n"
when we facing like this error:
TypeError: st object cannot be interpreted as an st
it usually because we use X instead len(X) in for loops
#error
for i in range(df.index):
pass
#currect
for i in range( len(df.index) ):
pass
list cannot be interpreted as an integer when using range
for i in range(list): -> will not work
for i in list: -> will work

Error casting to float, then int in python

Strange error happening.
I know of the issue with trying to cast strings with decimals directly into ints:
int(float('0.0'))
works, while
int('0.0')
does not. However, I'm still getting an error that I can't seem to figure out:
field = line.strip().split()
data[k,:] = [int(float(k)) for k in field[1:]]
ValueError: invalid literal for long() with base 10: '0.0'
Any ideas what could be happening here? The script seems to be thinking it's a cast to long instead of float. Any way to convince it otherwise?
Thanks in advance!
EDIT: the data line is of the form:
'c1c9r2r8\t0.0\t3.4\t2.1\t9.0\n'
It appears that what is happening is that the list comprehension is polluting your namespace.
eg.
k = 0
[k for k in range(10)]
After executing the above code in python 2.x the value of k will be 9 (the last value that was produced by range(10)).
I'll simplify your code to show you what is happening.
>>> l = [None, None, None]
>>> k = 0
>>> l[k] = [k for k in range(3)]
>>> print k, l
2 [None, None, [0, 1, 2]]
You see that l[k] evaluated to l[2] rather than l[0]. To avoid this namespace pollution either do not use the same variable names in a list comprehension as you do in the outer code, or use python 3.x where inner variables of list comprehensions no longer escape to the outer code.
For python 2.x your code should be modified to be something like:
data[k,:] = [int(float(_k)) for _k in field[1:]]
>>> line = 'c1c9r2r8\t0.0\t3.4\t2.1\t9.0\n'
>>> field = line.strip().split()
>>> field
['c1c9r2r8', '0.0', '3.4', '2.1', '9.0']
>>> [int(x) for x in map(float, field[1:])]
[0, 3, 2, 9]
Your error is coming from the left-hand side of the assignment data[k, :] = .... Here you're trying to index a NumPy array (data) with a string (k). NumPy tries to do an implicit conversion of that string to a usable integer index, and fails. For example:
>>> import numpy as np
>>> data = np.arange(12).reshape(3, 4)
>>> data['3.4', :] = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for long() with base 10: '3.4'
Use an integer instead of a string here, and the problem should go away.

How To Change Lists of Unicode to ASCII

I'm trying to change these lists I'm getting from my school grade site from Unicode to ASCII.
The lists look like this:
x = grades[1]
print x #Input
[u'B', u'84'] #Output
But I don't want the u in there. I've tried to use
a.encode('ascii','ignore')
But I get
Traceback (most recent call last):
File "C:\Python27\Project.py", line 33, in <module>
L1.encode('ascii','ignore')
AttributeError: 'list' object has no attribute 'encode'
is there anyway to do this?
The problem is that you're trying to encode a list full of strings, not a string. You can't call string methods on a list of strings; you have to call them on each string.
The pythonic way to do this is with a list comprehension:
>>> x = [u'B', u'84']
>>> y = [s.encode('ascii', 'ignore') for s in x]
>>> y
['B', '84']
Under the covers, this is basically the same as:
>>> x = [u'B', u'84']
>>> y = []
>>> for s in x:
... y.append(s.encode('ascii', 'ignore'))
>>> y
['B', '84']
But it's more concise, harder to get wrong, and (once you get the basic idea of list comprehensions) easier to read.
It's also the same as either of the following:
y = map(lambda s: s.encode('ascii', 'ignore'), x)
y = map(partial(unicode.encode, encoding='ascii', errors='ignore'), x)
Generally, if you need to write a lambda or non-trivial partial, a list comprehension will be more readable than a map call. But in cases where you have a function ready to use, map is often nicer.
You could simply apply the str() function to each element of your list. In python 2, str objects are ASCII encoded. For example (in a python shell):
>>> x = [u'B', u'84']
>>> x
[u'B', u'84']
>>> x[0]
u'B'
>>> x[1]
u'84'
>>> str(x[0])
'B'
>>> str(x[1])
'84'
And if a list is needed you can use a list comprehension :
>>> y = [str(i) for i in x]
>>> y
['B', '84']
or the map function:
>>> z = map(str, x)
>>> z
['B', '84']
>>>
Hope this is what your looking for. Regards!

Python error: could not convert string to float

I have some Python code that pulls strings out of a text file:
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854, ....]
Python code:
v = string[string.index('['):].split(',')
for elem in v:
new_list.append(float(elem))
This gives an error:
ValueError: could not convert string to float: [2.974717463860223e-06
Why can't [2.974717463860223e-06 be converted to a float?
You've still got the [ in front of your "float" which prevents parsing.
Why not use a proper module for that? For example:
>>> a = "[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> import json
>>> b = json.loads(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
or
>>> import ast
>>> b = ast.literal_eval(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
You may do the following to convert your string that you read from your file to a list of float
>>> instr="[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> [float(e) for e in instr.strip("[] \n").split(",")]
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
The reason your code is failing is, you are not stripping of the '[' from the string.
You are capturing the first bracket, change string.index("[") to string.index("[") + 1
This will give you a list of floats without the need for extra imports etc.
s = '[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]'
s = s[1:-1]
float_list = [float(n) for n in s.split(',')]
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
v = string[string.index('[') + 1:].split(',')
index() return index of given character, so that '[' is included in sequence returned by [:].

Categories