Merging items in a list - Python - python

Say I have a list in python, like such:
list=[1,2,3,4,5]
How would I merge the list so that it becomes:
list= [12345]
If anyone has a way to do this, it would be greatly appreciated!!

reduce(lambda x,y:10*x+y, [1,2,3,4,5])
# returns 12345

This probably better:
"%s" * len(L) % tuple(L)
which can handle:
>>> L=[1, 2, 3, '456', '7', 8]
>>> "%s"*len(L) % tuple(L)
'12345678'

>>> list=[1,2,3,4,5]
>>> k = [str(x) for x in list]
>>> k
['1', '2', '3', '4', '5']
>>> "".join(k)
'12345'
>>> ["".join(k)]
['12345']
>>>
>>> [int("".join(k))]
[12345]
>>>

list=[int("".join(map(str,list)))]

a = [1,2,3,4,5]
result = [int("".join(str(x) for x in a))]

Is this really what you mean by "merge the list"? You understand that a Python list can contain things other than numbers, right? You understand that Python is strongly typed, and will not let you "add" strings to numbers or vice-versa, right? What should the result be of "merging" the list [1, 2, "hi mom"] ?

[int(reduce(lambda x,y: str(x) + str(y),range(1,6)))]

Related

Changing a list into a string

I have a list like this:
li = [1, 2, 3, 4, 5]
I want to change it into a string, get rid of the quotes, and get rid of the commas so that it looks like this:
1 2 3 4 5
I tried the following:
new_list = []
new_list.append(li)
new_string = " ".join(new_list)
print new_string
however I get the below error:
TypeError: sequence item 0: expected str instance, int found
Why does this happen and how can I fix this so that I get the output I want?
The items in the list need to be of the str type in order to join them with the given delimeter. Try this:
' '.join(map(str, your_list)) # join the resulting iterable of strings, after casting ints
This is happening because join is expecting an iterable sequence of strings, and yours contains int.
You need to convert this list to string either by using list comprehension:
>>> li
[1, 2, 3, 4, 5]
>>> new_li = [str(val) for val in li]
>>> new_li
['1', '2', '3', '4', '5']
or a regular for loop:
>>> for x in range(len(li)):
... li[x] = str(li[x])
...
>>> li
['1', '2', '3', '4', '5']
then your expression will work.
>>> result = ' '.join(li)
>>> result
'1 2 3 4 5'
The error is from attempting to join integers into a string, you could do this to turn every value into a string, then join them.
new_list = [str(x) for x in li]
new_string = " ".join(new_list)
As a one-liner:
new_string = " ".join([str(x) for x in li])

I want to move a item to first index in list. How to simplify code?

This is my code.
lst=['0','1','2','3','4']
i = lst.index('2')
lst.pop(i)
tmp=[]
tmp.append('2')
tmp.extend(lst)
lst = tmp
print lst #output:['2','0','1','3','4']
Now I want to write pretty code. I think it may be to have room for improvement.So, I hope anyone who can explain and instruct me.Thanks!
sorted([0,1,2,3,4,5], key=lambda x: x == 2, reverse=True)
As an alternative answer you can use slicing :
>>> i = lst.index('2')
>>> ['2']+lst[:i]+lst[i+1:]
['2', '0', '1', '3', '4']
You can embed it inside a function :
>>> def move(elem,l):
... i = l.index(elem)
... return [elem]+lst[:i]+lst[i+1:]
...
>>> move('2',lst)
['2', '0', '1', '3', '4']
Donig it in place (altering the list):
lst = lst.pop(lst.index(2)) and (not lst.insert(0, 2)) and lst
Creating a new list for the result:
[2] + (lst.pop(lst.index(2)) and lst)

display a list values as a sequence of string

I have a list like
L=[[w,['0','0']],[r,['1']]]
I want to print it as
w = 00
r = 1
for getting this I tried like
for k in range(1,len(tab[0]))
print L[0][k][0],"=",(L[0][k][1])
but it prints like
w = ['0','0']
r = ['1']
can anyone help me? thanx in advance
In [5]: L=[['w',['0','0']],['r',['1']]]
In [6]: L1 = [item for item in L]
In [7]: L1
Out[7]: [['w', ['0', '0']], ['r', ['1']]]
In [8]: ['%s=%s' % (item[0], ''.join(item[1])) for item in L1]
Out[8]: ['w=00', 'r=1']
If the question is how do I convert ['0', '0'] to 00 then you may use join
for k in range(1,len(tab[0]))
print L[0][k][0],"=", ''.join((L[0][k][1]))
I don't fully understand the for loop (because I don't know what tab is) but to get string representation of a list, use join
Your list is wrong. Unless w and r are predefined variables, it should read as:
L=[['w',['0','0']],['r',['1']]]
In that case, the following will achieve the result:
for item in L:
print(item[0], ''.join(item[1]))
Just use a simple for-loop with string formatting:
L = [['w', ['0','0']], ['r',['1']]]
for item in L:
print '{} = {}'.format(item[0], ''.join(item[1]))
What ''.join() does it joins every item in the list separated by the '' (i.e nothing). So:
['0', '0'] --> '00'
Go with this..
L=[[w,['0','0']],[r,['1']]]
for item in L:
print item[0], '=', ''.join(item[1])
Ans:
w = 00
r = 1

Python: How can I take a list of lists, convert every element into strings, and return the list of lists?

For example:
list = [[11,2,3,5],[5,3,74,1,90]]
returns the same thing, only everything is a str instead of an int.
I want to be able to use .join on them. Thanks!
If you only ever go 2 lists deep:
>>> l = [[11, 2, 3, 5], [5, 3, 74, 1, 90]]
>>> [[str(j) for j in i] for i in l]
[['11', '2', '3', '5'], ['5', '3', '74', '1', '90']]
I'd use a list-comp and map for this one:
[ map(str,x) for x in lst ]
But I suppose py3.x would need an addition list in there (yuck).
[ list(map(str,x)) for x in lst ]
As a side note, you can't use join on this list we return anyway. I'm guessing you want to do something like this:
for x in lst:
print ("".join(x))
If that's the case, you can forgo the conversion all together and just do it when you're joining:
for x in lst:
print ("".join(str(item) for item in x))

How to convert list of intable strings to int

In Python, I want to convert a list of strings:
l = ['sam','1','dad','21']
and convert the integers to integer types like this:
t = ['sam',1,'dad',21]
I tried:
t = [map(int, x) for x in l]
but is showing an error.
How could I convert all intable strings in a list to int, leaving other elements as strings?
My list might be multi-dimensional. A method which works for a generic list would be preferable:
l=[['aa','2'],['bb','3']]
I'd use a custom function:
def try_int(x):
try:
return int(x)
except ValueError:
return x
Example:
>>> [try_int(x) for x in ['sam', '1', 'dad', '21']]
['sam', 1, 'dad', 21]
Edit: If you need to apply the above to a list of lists, why didn't you converted those strings to int while building the nested list?
Anyway, if you need to, it's just a matter of choice on how to iterate over such nested list and apply the method above.
One way for doing that, might be:
>>> list_of_lists = [['aa', '2'], ['bb', '3']]
>>> [[try_int(x) for x in lst] for lst in list_of_lists]
[['aa', 2], ['bb', 3]]
You can obviusly reassign that to list_of_lists:
>>> list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists]
How about using map and lambda
>>> map(lambda x:int(x) if x.isdigit() else x,['sam','1','dad','21'])
['sam', 1, 'dad', 21]
or with List comprehension
>>> [int(x) if x.isdigit() else x for x in ['sam','1','dad','21']]
['sam', 1, 'dad', 21]
>>>
As mentioned in the comment, as isdigit may not capture negative numbers, here is a refined condition to handle it notable a string is a number if its alphanumeric and not a alphabet :-)
>>> [int(x) if x.isalnum() and not x.isalpha() else x for x in ['sam','1','dad','21']]
['sam', 1, 'dad', 21]
I would create a generator to do it:
def intify(lst):
for i in lst:
try:
i = int(i)
except ValueError:
pass
yield i
lst = ['sam','1','dad','21']
intified_list = list(intify(lst))
# or if you want to modify an existing list
# lst[:] = intify(lst)
If you want this to work on a list of lists, just:
new_list_of_lists = map(list, map(intify, list_of_lists))
For multidimenson lists, use recursive technique may help.
from collections import Iterable
def intify(maybeLst):
try:
return int(maybeLst)
except:
if isinstance(maybeLst, Iterable) and not isinstance(lst, str):
return [intify(i) for i in maybeLst] # here we call intify itself!
else:
return maybeLst
maybeLst = [[['sam', 2],'1'],['dad','21']]
print intify(maybeLst)
Use isdigit() to check each character in the string to see if it is a digit.
Example:
mylist = ['foo', '3', 'bar', '9']
t = [ int(item) if item.isdigit() else item for item in mylist ]
print(t)
Use a list comprehension to validate the numeracy of each list item.
str.isnumeric won't pass a negative sign
Use str.lstrip to remove the -, check .isnumeric, and convert to int if it is.
Alternatively, use str.isdigit in place of .isnumeric.
Keep all values in the list
l = ['sam', '1', 'dad', '21', '-10']
t = [int(v) if v.lstrip('-').isnumeric() else v for v in l]
print(t)
>>> ['sam', 1, 'dad', 21, -10]
Remove non-numeric values
l = ['sam', '1', 'dad', '21', '-10']
t = [int(v) for v in t if v.lstrip('-').isnumeric()]
print(t)
>>> [1, 21, -10]
Nested list
l = [['aa', '2'], ['bb', '3'], ['sam', '1', 'dad', '21', '-10']]
t = [[int(v) if v.lstrip('-').isnumeric() else v for v in x] for x in l]
print(t)
>>> [['aa', 2], ['bb', 3], ['sam', 1, 'dad', 21, -10]]

Categories