如何将列表元素组合在元组中?
我正在努力结合元组中的特定列表元素。会喜欢任何反馈或帮助!我是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 ...>]
我觉得我的代码正确,但是我对此输出感到困惑。再次,如果这是一个愚蠢的问题,对不起。感谢任何帮助 - 谢谢!
I am struggling to combine specific list elements from a tuple. Would love any feedback or help! I am new to Python, so apologies if this is not a good question.
If I have a tuple list like this:
tuple_1 = [('A', 'B', 'C', 'D'), ('A', 'H'), ('B', 'C', 'D', 'A')]
I want to combine elements 'B', 'C', and 'D' from every tuple in the list:
tuple_1_new = [('A', 'BCD'), ('A', 'H'), ('BCD', 'A')]
My code looks like this:
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]
but when I print(tuple_1_new), it is giving me an output of:
[<tuple_iterator object at ...>, <tuple_iterator object at ...>, <tuple_iterator object at ...>]
I feel like my code is correct, but I'm confused with this output. Again, sorry if this is a dumb question. Would appreciate any help - thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一个解决方案,使用发电机:
打印:
Another solution, using generator:
Prints:
列表理解答案:
尽管没有完全获取所需的输出,但是打印:
注意:在“简单”列表中,'in itobles_name中的x for x for x in itsoble_name'distecting'defressing循环使用'x'(或如果扩展元组,则名称集合或在每个循环中执行ZIP提取)作为变量。
在列表理解中执行列表理解(对于循环内部的循环)中时,每个循环将贡献一个或多个变量,显然一定不能引起名称碰撞。
A list comprehension answer:
Although not quite getting the desired output, prints:
Note: In a 'simple' list comprehension, the 'for x in iterable_name' creates a processing loop using 'x' (or a collection of names if expanding a tuple or performing a zip extraction) as variable(s) in each loop.
When performing list comprehension within a list comprehension (for loop inside for loop), each loop will contribute one or more variables, which obviously must not incur a name collision.
假设字符串是您的示例中的单个字母:
或与重新恢复:
Assuming the strings are single letters like in your example:
Or with Regen: