When I use:
with open("test.txt") as file
read = csv.reader(file)
for i in read:
print(i)
and I have got something like that:
['[0', ' 0', ' 1', ' 0]']
and I need:
[0, 0, 1, 0]
Any advises please?
When I use:
with open("test.txt") as file
read = csv.reader(file)
for i in read:
print(i)
and I have got something like that:
['[0', ' 0', ' 1', ' 0]']
and I need:
[0, 0, 1, 0]
Any advises please?
ad = ['[0', ' 0', ' 1', ' 0]']
for i in range(len(ad)):
ad[i] = int(ad[i].replace("[", "").replace("]", ""))
print ad
[0, 0, 1, 0]
Normally, the easiest solution would be a list comprehension where new = [int(a) for a in old]
. However, in your case, the first and last elements of your list actually have brackets inside of them too.
Instead, you need to do something like:
new = [int("".join(filter(str.isdigit, a))) for a in old]
This is a pretty big one liner so lets break it down.
old
) and names it a
filter
command with the function str.isdigit
. This basically removes any character that isn't a digit. The issue with this, is that it returns an iterator and not a simple value."".join()
command to convert it to a simple string value. This string will only have the number.int
command which will transform your value into an int.If you don't like the one-liner, it can also be done this way:
new = []
for a in old:
filtered = filter(str.isdigit, a)
num_str = "".join(filtered)
num.append(int(num_str))
It's the same thing but a bit more verbose.
def parseToInt(s):
...: return int((s.replace('[', '')).replace(']', ''))
list(map(lambda x: parseToINt(x), a))