如何在元组中组合列表元素?



我正在努力从元组中组合特定的列表元素。希望得到任何反馈或帮助!我是Python的新手,所以如果这不是一个好问题,我很抱歉。

如果我有一个像这样的元组列表:

tuple_1 = [('A', 'B', 'C', 'D'), ('A', 'H'), ('B', 'C', 'D', 'A')]

我想组合列表中每个元组中的元素'B', 'C'和'D':

tuple_1_new = [('A', 'BCD'), ('A', 'H'), ('BCD', 'A')]

我的代码是这样的:

next_insert = [(iter(x)) for x in tuple_1]
tuple_1_new = [i + next(next_insert) + next(next_insert) if i == "B" else i for i in next_insert]

但是当我打印(tuple_1_new)时,它给我的输出是:

[<tuple_iterator object at ...>, <tuple_iterator object at ...>, <tuple_iterator object at ...>]

我觉得我的代码是正确的,但是我对这个输出感到困惑。再次抱歉,如果这是个愚蠢的问题。将感激任何帮助-谢谢!

def foo(arr):
w = "".join(arr)    
ind = w.find("BCD")
if ind >= 0:
ans = list(arr)
return tuple(ans[:ind] + ["BCD"] + ans[ind + 3:])
return arr
[foo(x) for x in tuple_1]
# [('A', 'BCD'), ('A', 'H'), ('BCD', 'A')]

另一个解决方案,使用generator:

tuple_1 = [("A", "B", "C", "D"), ("A", "H"), ("B", "C", "D", "A")]
def fn(x):
while x:
if x[:3] == ("B", "C", "D"):
yield "".join(x[:3])
x = x[3:]
else:
yield x[0]
x = x[1:]

out = [tuple(fn(t)) for t in tuple_1]
print(out)

打印:

[('A', 'BCD'), ('A', 'H'), ('BCD', 'A')]

一个列表理解式答案:

[tuple([t for t in tup if t not in ['B', 'C', 'D']] + [''.join([t for t in tup if t in ['B', 'C', 'D']])]) for tup in tuple_1]

虽然没有得到期望的输出,但是打印:

[('A', 'BCD'), ('A', 'H', ''), ('A', 'BCD')]

注意:在'简单'列表推导中,'for x In iterable_name'在每个循环中使用'x'(或扩展元组或执行zip提取时的名称集合)作为变量创建处理循环。当在列表推导中执行列表推导(for循环中的for循环)时,每个循环将提供一个或多个变量,显然不能导致名称冲突。

假设字符串是单个字母,如您的示例:

tuple_1_new = [tuple(' '.join(t).replace('B C D', 'BCD').split())
for t in tuple_1]

或with Regen:

tuple_1_new = [tuple(re.findall('BCD|.', ''.join(t)))
for t in tuple_1]