如何将嵌套列表列表转换为 python 3.3 中的元组列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18938276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:19:24 来源:igfitidea点击:
How to convert nested list of lists into a list of tuples in python 3.3?
提问by Mohammed
I am trying to convert a nested list of lists into a list of tuples in Python 3.3. However, it seems that I don't have the logic to do that.
我正在尝试将嵌套列表列表转换为 Python 3.3 中的元组列表。但是,我似乎没有这样做的逻辑。
The input looks as below:
输入如下所示:
>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]
And the desired ouptput should look as exactly as follows:
所需的输出应如下所示:
nested_lst_of_tuples = [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]
采纳答案by Martijn Pieters
Just use a list comprehension:
只需使用列表理解:
nested_lst_of_tuples = [tuple(l) for l in nested_lst]
Demo:
演示:
>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]
>>> [tuple(l) for l in nested_lst]
[('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]
回答by Ajit George
[tuple(l) for l in nested_lst]