如何在元组列表中连接元组中的列表?



每个元组中都有一个列表的元组列表:

[('22', ['de', 're']), ('11', ['c']), ('8, ['a', 'b', 'd', 'e'])]

整理我的字典后,我得到了它

dictionary = sorted(dictionary.items(), key=lambda x: x[0])
return dictionary

我想知道是否真的可以执行以下操作 目标是从中得到:

[('8, ['a', 'b', 'd', 'e']), ('11', ['c']), ('22', ['de', 're'])]

这:

[('8', 'a, b, d, e'), ('11', 'c'), ('22', 'de, re')]

试试这个:

lst=[('11', ['a', 'b', 'd', 'e']), ('22', ['c']), ('8', ['de', 're'])]
res=list(map(lambda x: tuple([x[0]]+ [", ".join([el for el in x[1]])]), lst))
print(res)

输出:

[('11', 'a, b, d, e'), ('22', 'c'), ('8', 'de, re')]
[Program finished]

您是否考虑过使用tuple()函数?此函数采用某种可迭代对象(在您的情况下为列表(,并返回包含该列表中值的元组。

这种理解应该是你要找的:

lst = [('11', ['a', 'b', 'd', 'e']), ('22', ['c']), ('8', ['de', 're'])]
res = [(n, ', '.join(s)) for n, s in lst]
print(res)

指纹:

[('11', 'a, b, d, e'), ('22', 'c'), ('8', 'de, re')]
def myFun(t):
return int(t[0])
a = [('22', ['de', 're']), ('11', ['c']), ('8', ['a', 'b', 'd', 'e'])]
sorted(a, key=myFun)

输出- [("8", ["a", "b", "d", "e"](, ("11", ["c"](, ("22", ["de", "re"](] 你可以试试这个

最新更新