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')
andtuple([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 indict
,list
and [set
] classes, and thecollections
module.
Related Topics
Pip Connection Failure: Cannot Fetch Index Base Url Http://Pypi.Python.Org/Simple/
How to Convert Defaultdict to Dict
Replace Column Values Based on Another Dataframe Python Pandas - Better Way
How to Remove Duplicates from a CSV File
Go to a Specific Line in Python
Sqlite3, Operationalerror: Unable to Open Database File
How to Get a List of Column Names in SQLite
Django What Is Reverse Relationship
How to Wrap Every Method of a Class
Typeerror: Cannot Create a Consistent Method Resolution Order (Mro)
How to Generate Random Numbers That Are Different
Python Module to Change System Date and Time
Finding Elements Not in a List
Pandas To_Datetime Parsing Wrong Year
Django Model Field Default Based Off Another Field in Same Model