How to Convert a List to a List of Tuples

How to convert a list to a list of tuples?

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

Convert list into list of tuples of every two elements

Fun with iter:

it = iter(l)
[*zip(it, it)] # list(zip(it, it))
# [(0, 1), (2, 3), (4, 5)]

You can also slice in strides of 2 and zip:

[*zip(l[::2], l[1::2]))]
# [(0, 1), (2, 3), (4, 5)]

How to convert a list to a list of tuples in scala?

I would do this like this:

List("k1","v1","k2","v2")
.grouped(2) // groups into a Lists of up to 2 elements
.collect { case List(a, b) => a -> b } // maps to tuples while dropping possible 1-element list
.toList // converts from Iterable to List

However, it would be perfectly doable without grouped:

list.foldLeft(List.empty[(String, String)] -> (None: Option[String])) {
case ((result, Some(key)), value) => (result :+ (key -> value)) -> None
case ((result, None), key) => result -> Some(key)
}._1

or

def isEven(i: Int) = i % 2 == 0

val (keys, values) = list.zipWithIndex.partition(p => isEven(p._2))

(key zip values).map { case ((k, _), (v, _)) => k -> v }

Of course if performance was really critical I would implement it in slightly different way to avoid allocations (e.g. by prepending results in foldLeft and reversing final results, or by using tailrec or ListBuffer).

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

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

Convert a list of lists back into a list of tuples

tuple(myList) will convert myList into a tuple, provided that myList is something iterable like a list, a tuple, or a generator.

To convert a lists of lists in a list of tuples, using a list comprehension expression:

last_list = [tuple(x) for x in Long_list]

or, to also perform your string replacement:

last_list = [tuple(y.replace('/', '@') for y in x) for x in Long_list]

From Python's reference:

tuple( [iterable] )

Return a tuple whose items are the same and in the same order as iterable‘s items. iterable may be a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For instance, tuple('abc') returns ('a', 'b', 'c') and tuple([1, 2, 3]) returns (1, 2, 3). If no argument is given, returns a new empty tuple, ().

tuple is an immutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. For other containers see the built in dict, list and [set] classes, and the collections module.



Related Topics



Leave a reply



Submit