Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

How to convert nested list of lists into a list of tuples in python 3.3?

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.

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')]
question from:https://stackoverflow.com/questions/18938276/how-to-convert-nested-list-of-lists-into-a-list-of-tuples-in-python-3-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...