Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Python's zip in C#?

Python's zip function does the following:

a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)

result

[[1, 6], [2, 7], [3, 8]]
like image 372
Jader Dias Avatar asked Mar 11 '10 17:03

Jader Dias


People also ask

What is Python zip () functions?

Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

How do I zip in Python?

Create a zip archive from multiple files in PythonCreate a ZipFile object by passing the new file name and mode as 'w' (write mode). It will create a new zip file and open it within ZipFile object. Call write() function on ZipFile object to add the files in it. call close() on ZipFile object to Close the zip file.

What does * mean in zip Python?

zip() built-in function From the official Python documentation, zip(*iterables) makes an iterator that aggregates elements from each of the iterators. Recap on unpacking operator(*) The single asterisk (*) means it unpacks the iterators.

How do you zip two tuples in Python?

If multiple iterables are passed, zip() returns an iterator of tuples with each tuple having elements from all the iterables. Suppose, two iterables are passed to zip() ; one iterable containing three and other containing five elements. Then, the returned iterator will contain three tuples.


2 Answers

How about this?

C# 4.0 LINQ'S NEW ZIP OPERATOR

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
        this IEnumerable<TFirst> first,
        IEnumerable<TSecond> second,
        Func<TFirst, TSecond, TResult> func);
like image 110
tanascius Avatar answered Sep 17 '22 06:09

tanascius


Solution 2: Similar to C# 4.0 Zip, but you can use it in C# 3.0

    public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
        this IEnumerable<TFirst> first,
        IEnumerable<TSecond> second,
        Func<TFirst, TSecond, TResult> func)
    {
        using(var enumeratorA = first.GetEnumerator())
        using(var enumeratorB = second.GetEnumerator())
        {
            while (enumeratorA.MoveNext())
            {
                enumeratorB.MoveNext();
                yield return func(enumeratorA.Current, enumeratorB.Current);
            }
        }
    }
like image 20
Jader Dias Avatar answered Sep 21 '22 06:09

Jader Dias