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]
Related
I have a list which looks like below
lis = '[-3.56568247e-02 -3.31957154e-02\n 7.04742894e-02\n 7.32413381e-02\n 1.74463019e-02]' (string type)
'\n' is also there in the list.
I need to convert this to actual list of integers
lis = [-3.56568247e-02,-3.31957154e-02 ,7.04742894e-02 ,7.32413381e-02, 1.74463019e-02] (list of integers)
I am doing the functionality, but it is failing
import as
res = ast.literal_eval(lis)
Can anyone tell me how to resolve this?
We can use re.findall along with a list comprehension:
lis = '[-3.56568247e-02 -3.31957154e-02 7.04742894e-02 7.32413381e-02\n 1.74463019e-02]'
output = [float(x) for x in re.findall(r'\d+(?:\.\d+)?(?:e[+-]\d+)?', lis)]
print(output)
# [0.0356568247, 0.0331957154, 0.0704742894, 0.0732413381, 0.0174463019]
You can try
[int(i) for i in lis.strip("[]").split(" ")]
You risk getting 1000 ways to do this.
This is a quick and easy way using only basic methods:
lis = '[1 2 3 4 5 77]'
elements = lis.replace('[','').replace(']','').split(' ')
my_ints = [int(e) for e in elements]
print(my_ints)
Example:
If there are two strings:-
s1 = 'cde'
s2 = 'abc'
Output: 'deab'
I converted the string into a list and compared two lists.
a = 'cde'
b = 'abc'
list1 = list(a)
list2 = list(b)
diff = []
for item in list1:
if item not in list2:
diff.append(item)
for item in list2:
if item not in list1:
diff.append(item)
diff = ' '.join(map(str, diff)).replace(' ','')
print(diff)
Is there any other way to solve this problem without converting it into the list?
I appreciate your help. Thanks in advance.
You can convert each string to a set then use symmetric_difference, then finally str.join back into a single string
>>> ''.join(set(a).symmetric_difference(b))
'daeb'
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']
(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()
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']