所以我正在尝试创建一个函数,它结合了元组的元素。
例如:
[(1,2),("Hi","Bye")]
将在函数实现后变为['12', 'HiBye']
。
我如何在Python中实现这一目标?
答案 0 :(得分:1)
对于配对,你可以这样做:
>>> list(map(lambda pair:"%s%s"%pair, [(1,2),("Hi","Bye")]))
['12', 'HiBye']
或者如果你想处理任意元组,而不仅仅是对:
>>> list(map(lambda l:''.join(map(str, l)), [(1,2),("Hi","Bye")]))
['12', 'HiBye']
>>> list(map(lambda l:''.join(map(str, l)), [(1,2,3),("Hi","Bye","Ciao")]))
['123', 'HiByeCiao']
答案 1 :(得分:0)
试试这个:
L = [(1, 2), ('Hi', 'Bye')]
L = list(map(lambda t : str(t[0]) + str(t[1]), L))
答案 2 :(得分:0)
尝试合并map()
和reduce()
:
import operator
lst = [("1", "2"), ("c", "d")]
map(lambda x: reduce(operator.concat, x, ""), lst)
匹配的项目必须是可连接的,即您需要将它们转换为例如首先是字符串或者将其包含在代码中:
import operator
lst = [(1, 2, 3, 52), ("c", "d")]
map(lambda x: reduce(operator.concat, map(str, x), ""), lst)
使用string.join()
也是可能的(也可能更加pythonic):
lst = [(1, 2, 3, 52), ("c", "d")]
map(lambda x: ''.join(map(str, x)), lst)
答案 3 :(得分:0)
使用列表理解:
myList = [(1,2),("Hi","Bye")]
answer = [str(t[0]) + str(t[1]) for t in myList]