我有一个这样的清单:
"\\1"
我想将元素list = [(1,'abc'),0.312,(2,'def'),0.122,(1,'abc'),0.999]
与(1, 'abc')
合并,因此输出应该如下:
0.312
任何人都可以帮助我吗?非常感谢!
答案 0 :(得分:7)
使用列表理解在压缩两个列表项后构建新元组:
l = [i+(j,) for i, j in zip(lst[::2], lst[1::2])]
print(l)
# [(1, 'abc', 0.312), (2, 'def', 0.122), (1, 'abc', 0.999)]
答案 1 :(得分:0)
我是python的新手。但试着解决这个问题。
以下是代码:
>>> list1 = [(1,'abc'),0.312,(2,'def'),0.122,(1,'abc'),0.999]
>>> list_output = list()
>>> t=f=None
>>> l = list()
>>> for i in list1:
... if type(i) == float:
... f = i
... if type(i) == tuple:
... t = i
... if t and f:
... for j in t:
... l.append(j)
... l.append(f)
... list_output.append(tuple(l))
... l = []
... t = f = None
...
>>>
>>>
>>> list_output
[(1, 'abc', 0.312), (2, 'def', 0.122), (1, 'abc', 0.999)]
如果您获得最佳解决方案,请告诉我