简体   繁体   English

合并列表中的项目 - Python

[英]Merging items in a list - Python

Say I have a list in python, like such: 假设我在python中有一个列表,如下所示:

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? 您了解Python列表可以包含除数字之外的其他内容,对吧? You understand that Python is strongly typed, and will not let you "add" strings to numbers or vice-versa, right? 您了解Python是强类型的,并且不会让您将“字符串”添加到数字中,反之亦然,对吧? What should the result be of "merging" the list [1, 2, "hi mom"] ? 结果如何“合并”清单[1, 2, "hi mom"]什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM