split space separated numeric string into a list in Python3 - python

Split space separated Numerical String into a List containing Numbers.
I want this:-
A = '5 2 12 4 29'
to be this in single line of code
B = [5,2,12,4,29]

You can also use the lambda function as following:
A = '5 2 12 4 29'
B = list(map(lambda x: int(x), a.split()))
print(B)
where split() returns a list of strings
and then map function iterates over each string where lambda function converts each string to Integer.

Try this
.split() method returns a list of splitted strings. So you can iterate over it and convert it to a integer
A = '5 2 12 4 29'
B = [int(l) for l in A.split()]
['5', '2', '12', '4', '29']
.split() method will return something like this. But you want them in integers. So you can follow the above method

You can use in python3 this style:
A = '5 2 12 4 29'
B = A.split(" ")
In this case, the split method, with the quotes is used to separate with spaces, as the A has number with spaces, then the quotes to separate would be split(" ")
print(B)
# ['5', '2', '12', '4', '29']

Here is a one-liner using a list comprehension:
A = '5 2 12 4 29'
B = [int(x) for x in A.split()]
print(B) # [5, 2, 12, 4, 29]

You can use split( ) to convert the string to a list of individual characters. ['5', '2', '12', '4', '29']
Since you want integers and not characters, you can use map() to convert those individual characters to integers.
A = '5 2 12 4 29'
B = list(map(int,A.split()))
print(B)
[5, 2, 12, 4, 29]

Related

.join() gives back list as a result in python

Could someone, please, explain why .join() behaves in the following way:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)
And the result is:
[ 1 , 0 , 5 , 3 , 4 , 1 2 , 1 9 ]
Not only is there still a list, but also an additional space.
How come?
When I use map() it works:
a = " ".join(list(map(str, input)))
But I would like to know what is wrong with the .join method I'm using.
str(input) returns one string '[1, 0, 5, 3, 4, 12, 19]', so then join uses each character of the string as input (a string is an iterable, like a list), effectively adding a space between each.
The effect is more visible if we join with a -: '[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'
In contrast, list(map(str, input)) converts each number to string, giving a list of strings (['1', '0', '5', '3', '4', '12', '19']), which join then converts to '1 0 5 3 4 12 19'
See #mozway's answer to understand .join()'s behavior.
To get what you want (using join), you should try this:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join([str(i) for i in input])
print(a)
Output:
1 0 5 3 4 12 19

Convert string with hard coded line breaks into matrix in python

I am trying to create a class that takes a string of digits with hard coded line breaks and outputs a matrix and details about that matrix. In the first instance i just want to be able to create the matrix but I am struggling. I'm aware that I could probably do this very easily with numpy or something similar but trying to practice.
class Matrix:
def __init__(self, matrix_string):
self.convert_to_list = [int(s) for s in str.split(matrix_string) if s.isdigit()]
self.split = matrix_string.splitlines()
I think i want to combine the two things I have already done but I cant figure out how to apply my convert_to_list method to every element in my split method.
Getting very confused.
SAMPLE INPUT/OUTPUT
Input = " 1 8 7 /n 6 18 2 /n 1 9 7 "
Desired Output = [[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It looks like you want a list of lists. For that you can use nested list comprehension.
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
lst = [[int(x) for x in r.split()] for r in s.split('/n')]
print(lst)
Output
[[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It's not that hard actually:
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
print([i.split() for i in s.split('/n')])
easier way but longer:
s = s.split('/n')
new = []
for i in s:
new.append(i.split())
print(new)
output:
[['1', '8', '7'], ['6', '18', '2'], ['1', '9', '7']]

Assigning numbers to given string's letters

I am currently trying to finish a project which wants encode given paragraph using given matrix. I wanted to start make a letter list:
letterlist = np.array([" ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"])
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY"
My goal is convert the letters to integer in order like A=1,B=2...Z=26 and " "=0. Then assign them to 1x3 arrays. like
But I couldn't even make a progress. First I tried make for loops to match same letter in the letter list and samplestr. Then if they are same, give the order in the letterlist as integer. But I didn't get any output.
for letter in samplestr:
for letter2 in letterlist:
if letter2==letter:
print("x") ## To see if I get any match
I don't know where did I wrong and how should I continue this. Would making dictionary make it easier to assign letters to integers? Need some advices. Thanks for your time.
The conversion to a number is done by converting the char to a ordinary number and then subtracting 64 because that is the starting ASCII-Index for 'A'
Code looks like this:
from math import ceil
samplestr = "MEET ME MONDAY"
# Pad string to be dividable by 3
samplestr = samplestr.ljust(ceil(len(samplestr)/3) * 3)
# "MEET ME MONDAY "
# Convert to number reprensentation
samplestr = [0 if c == ' ' else (ord(c)-64) for c in samplestr]
# [13, 5, 5, 20, 0, 13, 5, 0, 13, 15, 14, 4, 1, 25, 0]
# Split in chunks of 3
matrix = [samplestr[i:i+3] for i in range(0, len(samplestr), 3)]
print(matrix)
This produces the following output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Yes, dictionary will make it easier to assign letters to integers but if your final goal is to convert the letters to integer in order like A=1, B=2...Z=26 and " "=0, then assigning indices to the letters will also do the job.
I don't have much knowledge of numpy, so I will do it simply like this:
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY "
l = []
s = []
for i in samplestr:
s.append(letterlist2.index(i))
if len(s) == 3:
l.append(s)
s = []
if s != []:
l.append(s)
print(l)
Output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Use a dictionary (with a single list comprehension) to convert the letters to numbers (would probably be the fastest) and then reshape to have 3 columns (-1 will take care of number of rows):
convert = dict(zip(letterlist, np.arange(27)))
converted = np.array([convert[char] for char in samplestr])
#[13 5 5 20 0 13 5 0 13 15 14 4 1 25]
from math import ceil
#resize to closes upper multiple of 3
converted.resize(ceil(converted.size/3)*3)
#reshape to have 3 columns
converted = converted.reshape(-1,3)
output:
[[13 5 5]
[20 0 13]
[ 5 0 13]
[15 14 4]
[ 1 25 0]]
Here is another solution with a simple dictionary mapping and list comprehensions. Note that you don't need to hardcode letters, it's in the standard library.
from string import ascii_uppercase
chars = " " + ascii_uppercase
encode = {char:"{}".format(i) for i, char in enumerate(chars)}
def str2num(s):
return [[encode[char] for char in s[i:i+3]] for i in range(0, len(s), 3)]
s = "MEET ME MONDAY"
print(str2num(s))
which returns:
[['13', '5', '5'],
['20', '0', '13'],
['5', '0', '13'],
['15', '14', '4'],
['1', '25']]

Is there a built-in function to do the reverse of numpy.fromstring?

I just learned that numpy.fromstring() is a handy function:
a = ('1 2 3')
# convert to list of numbers
b = np.fromstring(a, sep=' ')
Now I modified the b and want to convert it back to a list of strings. Is there a built-in function in numpy to do that?
Sorry my original question might be not accurate. What I want to do is to convert b into the same format as a.
In [490]: a='1 2 3'
If you want b elements to be integers, as opposed to float, specify the dtype.
In [491]: b=np.fromstring(a, sep=' ',dtype=int)
In [492]: b
Out[492]: array([1, 2, 3])
In [493]: b += 2 # typical array math
In [494]: b
Out[494]: array([3, 4, 5])
Normal array display string, via print or str. Note that the array str omits the comma; that's just a visual clue distinguishing it from a list.
In [495]: print(b)
[3 4 5]
In [496]: str(b)
Out[496]: '[3 4 5]'
We can strip off the [] to get a display like a
In [497]: str(b)[1:-1]
Out[497]: '3 4 5'
But ' '.join is a good list formatting trick:
In [500]: [str(i) for i in b]
Out[500]: ['3', '4', '5']
In [501]: ' '.join([str(i) for i in b])
Out[501]: '3 4 5'
We could just as easily split a into a list of strings, modify those, and rejoin
In [506]: a1=a.split()
In [508]: a1
Out[508]: ['1', '2', '3']
In [509]: a1[1]='34'
In [510]: a1
Out[510]: ['1', '34', '3']
In [511]: ' '.join(a1)
Out[511]: '1 34 3'
According to these answers ans.1 & ans.2:
You can solve this by python itself or using numpy.
pure python solution:
map(str, b)
# ['1.0' '2.0' '3.0']
numpy solution:
list(np.char.mod('%d', b))
# ['1' '2' '3']
List comprehension solution:
' '.join(str(x) for x in b)
# '1.0 2.0 3.0'
or:
' '.join("%d" % x for x in b)
# '1 2 3'
Just figured (probably) the easiest way:
str(b)
:0)

Using raw_input in python for lists

I am trying to use raw_input in the python code to get user input of lists as below.
input_array.append(list(raw_input()));
User input as:
1 2 3 5 100
But the code is interpreting input as
[['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']]
Try: If I use plain input() instead of raw_input(), I am facing the issue in console.
"SyntaxError: ('invalid syntax', ('<string>', 1, 3, '1 2 3 4 100'))"
Note: I am not allowed to give the input in list format like
[1,2,3,5,100]
Could somebody please tell me how to proceed further.
>>> [int(x) for x in raw_input().split()]
1 2 3 5 100
[1, 2, 3, 5, 100]
>>> raw_input().split()
1 2 3 5 100
['1', '2', '3', '5', '100']
Creates a new list split by whitespace and then
[int(x) for x in raw_input().split()]
Converts each string in this new list into an integer.
list()
is a function that constructs a list from an iterable such as
>>> list({1, 2, 3}) # constructs list from a set {1, 2, 3}
[1, 2, 3]
>>> list('123') # constructs list from a string
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3] # constructs list from a tuple
so
>>> list('1 2 3 5 100')
['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']
also works, the list function iterates through the string and appends each character to a new list. However you need to separate by spaces so the list function is not suitable.
input takes a string and converts it into an object
'1 2 3 5 100'
is not a valid python object, it is 5 numbers separated by spaces.
To make this clear, consider typing
>>> 1 2 3 5 100
SyntaxError: invalid syntax
into a Python Shell. It is just invalid syntax. So input raises this error as well.
On an important side note:
input is not a safe function to use so even if your string was '[1,2,3,5,100]' as you mentioned you should not use input because harmful python code can be executed through input.
If this case ever arises, use ast.literal_eval:
>>> import ast
>>> ast.literal_eval('[1,2,3,5,100]')
[1, 2, 3, 5, 100]

Categories

Resources