Converting Strings to two lists in Python - python

(This is probably really simple, but) Say I have this input as a string:
"280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
and I want to separate each coordinate point onto separate lists, for each x and y value, so they'd end up looking like this:
listX = [280.2, 323.1, 135.8, 142.9]
listY = [259.8, 122.5, 149.5, 403.5]
I'd need this to be able to start out with any size string, thanks in advance!

Copy and paste this and it should work:
s_input = "280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
listX = [float(x.split(',')[0]) for x in s_input.split()]
listY = [float(y.split(',')[1]) for y in s_input.split()]

This would work.
my_string="280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
listX =[item.split(",")[0] for item in my_string.split()]
listY=[item.split(",")[1] for item in my_string.split()]
or
X_list=[]
Y_list=[]
for val in [item.split(",") for item in my_string.split()]:
X_list.append(val[0])
Y_list.append(val[1])
Which version to use would probably depend on your personal preference and the length of your string.

Have a look at the split method of strings. It should get you started.

You can do the following:
>>> a ="280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
>>> b = a.split(" ")
>>> b
['280.2,259.8', '323.1,122.5', '135.8,149.5', '142.9,403.5']
>>> c = [ x.split(',') for x in b]
>>> c
[['280.2', '259.8'], ['323.1', '122.5'], ['135.8', '149.5'], ['142.9', '403.5']]
>>> X = [ d[0] for d in c]
>>> X
['280.2', '323.1', '135.8', '142.9']
>>> Y = [ d[1] for d in c]
>>> Y
['259.8', '122.5', '149.5', '403.5']

There's a magical method call str.split, which given a string, splits by a delimiter.
Assume we have the string in a variable s.
To split by the spaces and make a list, we would do
coords = s.split()
At this point, the most straightforward method of putting it into the lists would be to do
listX = [float(sub.split(",")[0]) for sub in coords]
listY = [float(sub.split(",")[1]) for sub in coords]

You can use a a combination of zip and split with a list comprehension:
s = "280.2,259.8 323.1,122.5 135.8,149.5 142.9,403.5"
l = zip(*[a.split(',') for a in s.split()])
This will return a list of 2 tuples.
To get lists instead, use map on it.
l = map(list, zip(*[a.split(',') for a in s.split()]))
l[0] and l[1] will have your lists.
if your list is huge, consider using itertools.izip()

Related

How to convert an integer to a list in python?

I have an integer object for example a = 1234 and I want to convert it to a list, so it would look something like [1234].
I tried converting it into a string first and then converting it to a list but that gives me [1,2,3,4].
Any suggestions?
You can just cover it in brackets.
a = 1234
print([a])
Or append()
b = []
b.append(a)
output
[1234]
Here:
a = 1234
lst = []
lst.append(a)
print(lst) #[1234]
If you are trying to convert in to string, use str()
>>> str(1234)
'1234'
If you are trying to put your int in a list, use []:
>>> var = 1234
>>> [var]
[1234]
or do:
>>> l = []
>>> l.append(var)
>>> l
[1234]
Just cover it with brackets:
a=1243
a=[a]
or create a list and append a
b = []
b.append(a) # or you could do b=[a]

Join characters from list of strings by index

For example, I have the following list.
list=['abc', 'def','ghi','jkl','mn']
I want to make a new list as:
newList=['adgjm','behkn','cfil']
picking every first character of each element forming a new string then appending into the new list, and then with the second character of every element and so on:
Thanks for the help.
One way is zipping the strings in the list, which will interleave the characters from each string in the specified fashion, and join them back with str.join:
l = ['abc', 'def','ghi','jkl']
list(map(''.join, zip(*l)))
# ['adgj', 'behk', 'cfil']
For strings with different length, use zip_longest, and fill with an empty string:
from itertools import zip_longest
l = ['abcZ', 'def','ghi','jkl']
list(map(''.join, zip_longest(*l, fillvalue='')))
# ['adgj', 'behk', 'cfil', 'Z']
You can try this way:
>>> list1 =['abc', 'def','ghi','jkl']
>>> newlist = []
>>> for args in zip(*list1):
... newlist.append(''.join(args))
...
>>> newlist
['adgj', 'behk', 'cfil']
Or using list comprehension:
>>> newlist = [''.join(args) for args in zip(*list1)]
>>> newlist
['adgj', 'behk', 'cfil']
You can try this:
list=['abc', 'def','ghi','jkl']
n = len(list[0])
newList = []
i = 0
for i in range(n):
newword = ''
for word in list:
newword += word[i]
newList.append(newword)
print(newList)

Cut character string every two commas

I would like to separate my string every both commas but I can not, can you help me.
This is what I want: ['nb1,nb2','nb3,nb4','nb5,nb6']
Here is what I did :
a= 'nb1,nb2,nb3,nb4,nb5,nb6'
compteur=0
for i in a:
if i==',' :
compteur+=1
if compteur%2==0:
print compteur
test = a.split(',', compteur%2==0 )
print a
print test
The result:
2
4
nb1,nb2,nb3,nb4,nb5,nb6
['nb1', 'nb2,nb3,nb4,nb5,nb6']
Thanks you by advances for you answers
You can use regex
In [12]: re.findall(r'([\w]+,[\w]+)', 'nb1,nb2,nb3,nb4,nb5,nb6')
Out[12]: ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
A quick fix could be to simply first separate the elements by commas and then join the elements by two together again. Like:
sub_result = a.split(',')
result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
This gives:
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
This will also work if the number of elements is odd. For example:
>>> a = 'nb1,nb2,nb3,nb4,nb5,nb6,nb7'
>>> sub_result = a.split(',')
>>> result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6', 'nb7']
You use a zip operation of the list with itself to create pairs:
a = 'nb1,nb2,nb3,nb4,nb5,nb6'
parts = a.split(',')
# parts = ['nb1', 'nb2', 'nb3', 'nb4', 'nb5', 'nb6']
pairs = list(zip(parts, parts[1:]))
# pairs = [('nb1', 'nb2'), ('nb2', 'nb3'), ('nb3', 'nb4'), ('nb4', 'nb5'), ('nb5', 'nb6')]
Now you can simply join every other pair again for your output:
list(map(','.join, pairs[::2]))
# ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
Split the string by comma first, then apply the common idiom to partition an interable into sub-sequences of length n (where n is 2 in your case) with zip.
>>> s = 'nb1,nb2,nb3,nb4,nb5,nb6'
>>> [','.join(x) for x in zip(*[iter(s.split(','))]*2)]
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']

Create a list of consequential alphanumeric elements

I have
char=str('DOTR')
and
a=range(0,18)
How could I combine them to create a list with:
mylist=['DOTR00','DOTR01',...,'DOTR17']
If I combine them in a for loop then I lose the leading zero.
Use zfill:
>>> string = "DOTR"
>>> for i in range(0, 18):
... print("DOTR{}".format(str(i).zfill(2)))
...
DOTR00
DOTR01
DOTR02
DOTR03
DOTR04
DOTR05
DOTR06
DOTR07
DOTR08
DOTR09
DOTR10
DOTR11
DOTR12
DOTR13
DOTR14
DOTR15
DOTR16
DOTR17
>>>
And if you want a list:
>>> my_list = ["DOTR{}".format(str(i).zfill(2)) for i in range(18)]
>>> my_list
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
>>>
You can do it using a list comprehension like so:
>>> mylist = [char+'{0:02}'.format(i) for i in a]
>>> mylist
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
Simply use list comprehension and format:
mylist = ['DOTR%02d'%i for i in range(18)]
Or given that char and a are variable:
mylist = ['%s%02d'%(char,i) for i in a]
You can, as #juanpa.arrivillaga also specify it as:
mylist = ['{}{:02d}'.format(char,i) for i in a]
List comprehension is a concept where you write an expression:
[<expr> for <var> in <iterable>]
Python iterates over the <iterable> and unifies it with <var> (here i), next it calls the <expr> and the result is appended to the list until the <iterable> is exhausted.
can do like this
char = str('DOTR')
a=range(0,18)
b = []
for i in a:
b.append(char + str(i).zfill(2))
print(b)

python add string to the start of each element in array

In the following i have an array where for each element a string should be added at the start and not append ,how can i do this
a=["Hi","Sam","How"]
I want to add "Hello" at the start of each element so that the output will be
Output:
a=["HelloHi","HelloSam","HelloHow"]
This works for a list of strings:
a = ['Hello'+b for b in a]
and this works for other objects too (uses their strings representation):
a = ['Hello{}'.format(b) for b in a]
Example:
a = ["Hi", "Sam", "How", 1, {'x': 123}, None]
a = ['Hello{}'.format(b) for b in a]
# ['HelloHi', 'HelloSam', 'HelloHow', 'Hello1', "Hello{'x': 123}", 'HelloNone']
a=["Hi","Sam","How"]
a = ["hello" + x for x in a]
print a
or you can use map:
map('Hello{0}'.format,a)
Another option:
>>> def say_hello(foo):
... return 'Hello{}'.format(foo)
...
>>> map(say_hello,['hi','there'])
['Hellohi', 'Hellothere']

Categories

Resources