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
158 views
in Technique[技术] by (71.8m points)

python - How to convert a list to a list of tuples?

I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.

This is the input list:

L = [1,term1, 3, term2, x, term3,... z, termN]

and I want to convert this list to a list of tuples (or directly to a dictionary) like this:

[(1, term1), (3, term2), (x, term3), ...(z, termN)]

How can we do that easily in Python?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]

You want to group three items at a time?

>>> zip(it, it, it)

You want to group N items at a time?

# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)

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

...