Is there a zip function to create tuples with more than 2 elements?
No, zip
for an arbitrary number of sequences isn't currently possible due to Swift's lack of variadic generics. This is discussed in the Generics Manifesto.
In the meanwhile, I wrote a gyb
template for generating ZipSequences of custom arity. I've also pre-generated ZipSequences of arity 3...10
for your convenience. It's available here.
In action:
let integers = [1, 2, 3, 4, 5]
let strings = ["a", "b", "c", "d", "e"]
let doubles = [1.0, 2.0, 3.0, 4.0, 5.0]
for (integer, string, double) in zip(integers, strings, doubles) {
print("\(integer) \(string) \(double)")
}
Prints:
1 a 1.0
2 b 2.0
3 c 3.0
4 d 4.0
5 e 5.0
Zip with list output instead of tuple
If you are zipping more than 2 lists (or even only 2, for that matter), a readable way would be:
[list(a) for a in zip([1,2,3], [4,5,6], [7,8,9])]
This uses a list comprehension to apply list
to each element (tuple) in the list, converting them into lists.
Get a tuple from lists with zip() in Python
Don't put []
around the variables. Now you're zipping those lists, not the contents of the variables.
Just use:
answer = tuple(zip(name, place, weather))
zip function help with tuples
>>> zip((1,2,3),(10,20,30),(100,200,300))
[(1, 10, 100), (2, 20, 200), (3, 30, 300)]
>>> [sum(x) for x in zip((1,2,3),(10,20,30),(100,200,300))]
[111, 222, 333]
To do this with an arbitrarily large set of tuples:
>>> myTuples = [(1,2,3), (10,20,30), (100,200,300)]
>>> [sum(x) for x in zip(*myTuples)]
[111, 222, 333]
sidenote: in python3, note that zip returns a lazy iterable, which you can always explicitly turn into a list like any other kind of iterable: list(zip(...))
(thanks to Seganku for catching mistake in examples in an edit which was thrice rejected by other editors)
Python make list of tuples from two lists and a constant
You could use itertools.repeat
:
from itertools import repeat
ob = list(zip(repeat(constant), A, B))
Sum of tuples in python using zip()
You can use a dict comprehension with each value produced from a sum of a generator expression:
{k: tuple(sum(t) for t in zip(*l)) for k, l in dict0.items()}
This returns:
{'ABX': (1, 9), 'ABD': (4, 1), 'ABY': (21, 4), 'ABR': (16, 5)}
Add together lists of tuples
For a pure-Python approach you can use operator.add(a, b) (returns a + b
) from the operator
module combined with the built-in functions map(function, iterable, ...) and zip(*iterables, strict=False). The map
function "[r]eturn[s] an iterator that applies function to every item of iterable, yielding the results" and the zip
function iterates over several iterables in parallel, successively yielding tuples of these elements.
import operator
xList = [(1, 2), (3,4)]
yList = [(5, 6), (7, 8)]
res = [tuple(map(operator.add, a, b)) for a, b in zip(xList, yList)]
print(res)
Output
[(6, 8), (10, 12)]
List of lists of tuples, sum element-wise
You could do this pretty easily with numpy. Use sum on axis 0.
import numpy as np
l = [
[(3, 5), (4, 5), (4, 5)],
[(7, 13), (9, 13), (10, 13)],
[(5, 7), (6, 7), (7, 7)]
]
[tuple(x) for x in np.sum(l,0)]
Output
[(15, 25), (19, 25), (21, 25)]
Zip lists in Python
When you zip()
together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple.
See for yourself:
In [1]: a = b = c = range(20)
In [2]: zip(a, b, c)
Out[2]:
[(0, 0, 0),
(1, 1, 1),
...
(17, 17, 17),
(18, 18, 18),
(19, 19, 19)]
To find out how many elements each tuple contains, you could examine the length of the first element:
In [3]: result = zip(a, b, c)
In [4]: len(result[0])
Out[4]: 3
Of course, this won't work if the lists were empty to start with.
Related Topics
Alamofire Asynchronous Completionhandler For Json Request
Swiftui: Pop to Root View When Selected Tab Is Tapped Again
Swift - Custom Setter on Property
Println Dictionary Has "Optional"
Urlsession.Shared.Datataskpublisher Not Working on iOS 13.3
Multiple Type Constraints in Swift
Hide Navigation Bar Without Losing Swipe Back Gesture in Swiftui
How to Create Dictionary That Can Hold Anything in Key? or All the Possible Type It Capable to Hold
Convert Avaudiopcmbuffer to Nsdata and Back
How to Create a View-Based Nstableview Purely in Code
Checking for Nil Value in Swift Dictionary Extension
Uitableviewautomaticdimension Not Working for Resizing Cell Height
Swift Date(Byadding:To:) Returns Nil for Trivial Calculation in Repl
Closure Use of Non-Escaping Parameter May Allow It to Escape
Uploading Image to Firebase Storage and Database
How to Convert Range in Nsrange
Swift: How to Read Standard Output in a Child Process Without Waiting for Process to Finish