Merging items in a list - 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 app开发者_Go百科reciated!!
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)))]
精彩评论