python-linq-samples

所属分类:Python编程
开发工具:C#
文件大小:0KB
下载次数:0
上传日期:2019-01-04 09:23:54
上 传 者sh-1993
说明:  Python-Linq示例:C#Linq函数编程与Python的比较,
(Python Linq Examples: Comparision of C# Linq functional programming to Python,)

文件列表:
.DS_Store (8196, 2019-01-04)
Customers.json (136570, 2019-01-04)
Customers.xml (143940, 2019-01-04)
pubspec.lock (87, 2019-01-04)
pubspec.yaml (91, 2019-01-04)
src/ (0, 2019-01-04)
src/csharp/ (0, 2019-01-04)
src/csharp/LinqSamples101.sln (7430, 2019-01-04)
src/csharp/linq-aggregate/ (0, 2019-01-04)
src/csharp/linq-aggregate/Program.cs (10955, 2019-01-04)
src/csharp/linq-aggregate/linq-aggregate.csproj (364, 2019-01-04)
src/csharp/linq-conversion/ (0, 2019-01-04)
src/csharp/linq-conversion/Program.cs (2458, 2019-01-04)
src/csharp/linq-conversion/linq-conversion.csproj (365, 2019-01-04)
src/csharp/linq-element/ (0, 2019-01-04)
src/csharp/linq-element/Program.cs (2684, 2019-01-04)
src/csharp/linq-element/linq-element.csproj (362, 2019-01-04)
src/csharp/linq-generation/ (0, 2019-01-04)
src/csharp/linq-generation/Program.cs (1233, 2019-01-04)
src/csharp/linq-generation/linq-generation.csproj (365, 2019-01-04)
src/csharp/linq-grouping/ (0, 2019-01-04)
src/csharp/linq-grouping/Program.cs (5827, 2019-01-04)
src/csharp/linq-grouping/linq-grouping.csproj (363, 2019-01-04)
src/csharp/linq-join/ (0, 2019-01-04)
src/csharp/linq-join/Program.cs (4231, 2019-01-04)
src/csharp/linq-join/linq-join.csproj (359, 2019-01-04)
src/csharp/linq-miscellaneous/ (0, 2019-01-04)
src/csharp/linq-miscellaneous/Program.cs (2433, 2019-01-04)
src/csharp/linq-miscellaneous/linq-miscellaneous.csproj (368, 2019-01-04)
src/csharp/linq-ordering/ (0, 2019-01-04)
src/csharp/linq-ordering/Program.cs (6301, 2019-01-04)
src/csharp/linq-ordering/linq-ordering.csproj (363, 2019-01-04)
src/csharp/linq-partitioning/ (0, 2019-01-04)
src/csharp/linq-partitioning/Program.cs (5091, 2019-01-04)
src/csharp/linq-partitioning/linq-partitioning.csproj (367, 2019-01-04)
src/csharp/linq-projections/ (0, 2019-01-04)
src/csharp/linq-projections/Program.cs (9857, 2019-01-04)
src/csharp/linq-projections/linq-projections.csproj (366, 2019-01-04)
... ...

101 LINQ Samples in Python ======================== Port of the [C# 101 LINQ Samples](http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b) rewritten into modern C# syntax and then also using Python, using built in methods where possible. Python doesn't really lend itself well to functional programming because is functional methods are really procedural. There is support for lambda expressions, but you can't chain or compose your your functional operations very well as you will see compare to C# equivalent below. Source for both C# and Python are included in the [src](src) folder in this repository - To run the respective C# projects (*.csproj*), open the containing folder in [Visual Studio Code](https://code.visualstudio.com/) use the Debug command - To run the respective Python files (*.py*), open the file in [Visual Studio Code](https://code.visualstudio.com/) use the *Run Python File in Terminal* right click menu command (requirses the Python extension) ### Operation Comparison Matrix |Operation|C#|python|Comment| |---------|--|----|-------| |**Filter**|`Where`|`(x for x in sequence if fiter(x))`|Can also use `filter(f(x), sequence)`| |**Projection**|`Select`|`(f(x) for x in sequence)`|Can also use `map(f(x), sequence)`| ||`SelectMany`|`(f(x, y) for x in sequence1 for y in sequence2)`||| |**Partitioning**|`Take(n)`|`array[:n]`|| ||`TakeWhile(predicate)`|`takewhile(predicate)`|`from itertools import takewhile`| ||`Skip(n)`|`array[n:]`|| ||`SkipWhile(predicate)`|`dropwhile(predicate, sequence)`|`from itertools import dropwhile`| |**Ordering**|`OrderBy`|`sequence.sort()`
*or*
`sorted(sequence)`|| ||`OrderBy(lambda)`|`sequence.sort(key=lambda)`
*or*
`sorted(sequence, key=lambda)`|| ||`OrderByDescending`|`sequence.sort(reverse=True)`
*or*
`sorted(sequence, reverse=True)`|| ||`OrderByDescending(lambda)`|`sequence.sort(key=lambda, reverse=True)`
*or*
`sorted(sequence, key=lambda, reverse=True)`|| ||`ThenBy`|`sequence.sort(key=lambda (key1, key2))`
*or*
`sorted(sequence, key=lambda (key1, key))`|| ||`ThenByDescending`|`sequence.sort(key=lambda (key1, -key2))`
*or*
`sorted(sequence, key=lambda (key1, -key2))`
*or use a 2 pass sort, starting with least significant*
`ordered = sorted(unordered, key=lambda (key2))`
`ordered = sorted(ordered, key=lambda (key1))` | ||`Reverse`|`sequence.reverse()`
*or*
`reversed(sequence)`|| |**Grouping**|`GroupBy`|`groupby`|`from itertools. import groupby`
Grouping works on sorted sequences
Once you've iterated over the grouping, you can't access it again, its empty |**Sets**|`Distinct`|`set`|or Set comprehension
{x for x in sequence} ||`Union`|`union`|| ||`Interect`|`intersection`|| ||`Except`|`difference`|| |**Conversion**|`ToArray`|`list`|| ||`ToList`|`list`|| ||`ToDictionary`|`{key:value for (key,value) in sequence}`|or use `dict` in conjuction with `zip`| ||`OfType`|`'filter` using `isinstance` as predicate| |**Element**|`First`|`next`|| ||`First(lambda)`|`next(list)`|`next(filter(lambda)`| ||`FirstOrDefault`|`next(list)`|`next(filter(lambda), default)`| ||`ElementAt`|`list[0]`|| |**Generation**|`Enumerable.Range`|range| ||`Enumerable.Repeat`|`[x] * n`
*or*
`repeat(x, n)`|`from itertools import repeat`| |**Quantifiers**|`Any`|`any`|| ||`All`|`all`|| |**Aggregate**|`Count`|`len` || ||`Count(lamda)`|`sum(1, iterator)`|| ||`Sum`|`sum`|| ||`Min`|`min`|| ||`Max`|`max`|| ||`Avg`||Custom calculation using `sum` / `len`| ||`Sum(lambda)`|`sum(iterator)`|| ||`Min(lambda)`|`min(iterator)`|| ||`Max(lambda)`|`max(iterator)`|| ||`Avg(lambda)`||Custom calculation using
`sum(iterator)` / `len`| ||`Aggregate`|`reduce(lambda, sequence)`|`from functools import reduce`| ||`Aggregate(seed, lamda)`|`reduce(lambsa,seed,sequence)`|`from functools import reduce`| |**Miscellaneous**|`Concat(IEnumerable)`|`list1 + list2`|| ||`SequenceEqual(IEnumerable)`|`list1==list2`|| #### Source |Operation/Section|Python Source|C# Source| |-----------------|-------------|---------| |[Filter](#linq1-where---simple-1)|[linq-restrictions.py](src/python/linq-restrictions.py)|[linq-restrictions/Program.cs](src/csharp/linq-restrictions/Program.cs)| |[Projection](#linq---projection-operators)|[linq-projections.py](src/python/linq-projections.py)|[linq-projections/Program.cs](src/csharp/linq-projections/Program.cs)| |[Partitioning](#linq---partitioning-operators)|[linq-partitions.py](src/python/linq-partitions.py)|[linq-partitioning/Program.cs](src/csharp/linq-partitioning/Program.cs)| |[Ordering](#linq---ordering-operators)|[linq-ordering.py](src/python/linq-ordering.py)|[linq-ordering/Program.cs](src/csharp/linq-ordering/Program.cs)| |[Grouping](#linq---grouping-operators)|[linq-grouping.py](src/python/linq-grouping.py)|[linq-grouping/Program.cs](src/csharp/linq-grouping/Program.cs)| |[Set](#linq---set-operators)|[linq-setoperators.py](src/python/set-operators.py)|[linq-sets/Program.cs](src/csharp/linq-sets/Program.cs)| |[Conversion](#linq---conversion-operators)|[linq-conversion.py](src/python/linq-conversion.py)|[linq-conversion/Program.cs](src/csharp/linq-conversion/Program.cs)| |[Element](#linq---element-operators)|[linq-element.py](src/python/linq-element.py)|[linq-element/Program.cs](src/csharp/linq-element/Program.cs)| |[Generation](#linq---generation-operators)|[generationon.py](src/python/linq-generation.py)|[linq-generation/Program.cs](src/csharp/linq-generation/Program.cs)| |[Quantifiers](#linq---quantifiers)|[linq-quantifiers.py](src/python/linq-quantifiers.py)|[linq-quantifiers/Program.cs](src/csharp/linq-quantifiers/Program.cs)| |[Aggregate](#linq---aggregate-operators)|[linq-aggregate.py](src/python/linq-aggregate.py)|[linq-aggregate/Program.cs](src/csharp/linq-aggregate/Program.cs)| |[Miscellaneous](#linq---miscellaneous-operators)|[linq-miscellaneous.py](src/python/linq-miscellaneous.py)|[linq-miscellaneous/Program.cs](src/csharp/linq-miscellaneous/Program.cs)| |[Query](#linq---query-execution)|[linq-query.py](src/python/linq-query.py)|[linq-query/Program.cs](src/csharp/linq-query/Program.cs)| ## Side-by-side - C# LINQ vs python functional collections For a side-by-side comparison, the original **C#** source code is displayed above the equivalent **python** translation. - The **Output** shows the console output of running the **python** sample. - Outputs ending with `...` illustrates only a partial response is displayed. - The source-code for C# and python utils used are included once under the first section they're used in. - The C# ObjectDumper util used is downloadable from MSDN - [ObjectDumper.zip](http://code.msdn.microsoft.com/Visual-Studio-2008-C-d295cdba/file/46086/1/ObjectDumper.zip) - Where I haven't been able to figure out the Python implemention, I've created an empty function like this: ```python def f: pass ``` LINQ - Filter Operators ----------------------- ### linq1: Where - Simple 1 > This sample uses a filter to find all elements of an array with a value less than 5. ```csharp //c# static void Linq1() { var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = numbers.Where(n => n < 5); Console.WriteLine("Numbers < 5:"); lowNums.ForEach(Console.WriteLine); } ``` ```python #python def linq1(): numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0] low_nums = (x for x in numbers if x < 5) print("Numbers < 5:") shared.printN(low_nums) ``` #### Output Numbers < 5: 4 1 3 2 0 ### linq2: Where - Simple 2 >This sample uses a filter to find all products that are out of stock. ```csharp //c# static void Linq2() { var products = GetProductList(); var soldOutProducts = products.Where(p => p.UnitsInStock == 0); Console.WriteLine("Sold out products:"); soldOutProducts.ForEach(x => Console.WriteLine($"{x.ProductName} is sold out!")); } ``` ```python #python def linq2(): products = shared.getProductList() sold_out_products = (x for x in products if x.UnitsInStock == 0) print("Sold out products:") for item in sold_out_products: print("%s is sold out!" % item.ProductName) ``` #### Output Sold out products: Chef Anton's Gumbo Mix is sold out! Alice Mutton is sold out! Thringer Rostbratwurst is sold out! Gorgonzola Telino is sold out! Perth Pasties is sold out! ### linq3: Where - Simple 3 >This sample uses a filter to find all products that are in stock and cost more than 3.00 per unit. ```csharp //c# public static void Linq3() { var products = GetProductList(); var expensiveInStockProducts = products.Where(p => p.UnitsInStock > 0 && p.UnitPrice > 3.00M); Console.WriteLine("In-stock products that cost more than 3.00:"); expensiveInStockProducts.ForEach(product => Console.WriteLine($"{product.ProductName} is in stock and costs more than 3.00.")); } ``` ```python #python def linq3(): products = shared.getProductList() expensive_in_stock_products = (x for x in products if x.UnitsInStock > 0 and x.UnitPrice > 3.0000) print("In-stock products that cost more than 3.00:") for item in expensive_in_stock_products: print("%s is in stock and costs more than 3.00." % item.ProductName) ``` #### Output In-stock products that cost more than 3.00: Chai is in stock and costs more than 3.00. Chang is in stock and costs more than 3.00. Aniseed Syrup is in stock and costs more than 3.00. ... ### linq4: Where - Drilldown >This sample uses a filter to find all customers in Washington and then it uses a foreach loop to iterate over the orders collection that belongs to each customer. ```csharp //c# static void Linq4() { var customers = GetCustomerList(); Console.WriteLine("Customers from Washington and their orders:"); var waCustomers = customers.Where(c => c.Region == "WA"); waCustomers.ForEach((customer) => { Console.WriteLine($"Customer {customer.CustomerID}: {customer.CompanyName}"); customer.Orders.ForEach((order) => { Console.WriteLine($" Order {order.OrderID}: {order.OrderDate}"); }); }); } ``` ```python #python def linq4(): customers = shared.getCustomerList() wa_customers = (x for x in customers if x.Region == "WA") print("Customers from Washington and their orders:") for customer in wa_customers: print("Customer %s : %s" % (customer.CustomerID, customer.CompanyName)) for order in customer.Orders: print(" Order %s: %s" % (order.OrderID, order.OrderDate)) ``` #### Output Customers from Washington and their orders: Customer LAZYK: Lazy K Kountry Store Order 10482: 1997-03-21T00:00:00 Order 10545: 1997-05-22T00:00:00 Customer TRAIH: Trail's Head Gourmet Provisioners Order 10574: 1997-06-19T00:00:00 Order 10577: 1997-06-23T00:00:00 Order 10822: 1998-01-08T00:00:00 ... ### linq5: Where - Indexed >This sample demonstrates an indexed filter that returns digits whose name is shorter than their value. ```csharp //c# static void Linq5() { var digits = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var shortDigits = digits.Where((digit, index) => digit.Length < index); Console.WriteLine("Short digits:"); shortDigits.ForEach(d => Console.WriteLine($"The word {d} is shorter than its value.")); } ``` ```python #python def linq5(): digits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] index = 0 # Lambdas cant have multiple lines, so create a filter function def filter_func(digit): nonlocal index result = len(digit) < index index += 1 return result short_digits = filter(filter_func, digits) print("Short digits:") for d in short_digits: print("The word %s is shorter than its value." % d) ``` #### Output Short digits: The word five is shorter than its value. The word six is shorter than its value. The word seven is shorter than its value. The word eight is shorter than its value. The word nine is shorter than its value. LINQ - Projection Operators --------------------------- ### linq6: Select - Simple 1 >This sample projects a sequence of ints 1+ higher than those in an existing array of ints. ```csharp //c# static void Linq6() { var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsPlusOne = numbers.Select(n => n + 1); Console.WriteLine("Numbers + 1:"); numsPlusOne.ForEach(Console.WriteLine); } ``` ```python #python def linq6(): numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0] nums_plus_one = (n+1 for n in numbers) print("Numbers + 1:") shared.printN(nums_plus_one) ``` #### Output Numbers + 1: 6 5 2 4 10 9 7 8 3 1 ### linq7: Select - Simple 2 >This sample projects a sequence of just the names of a list of products. ```csharp //c# static void Linq7() { var products = GetProductList(); var productNames = products.Select(p => p.ProductName); Console.WriteLine("Product Names:"); productNames.ForEach(Console.WriteLine); } ``` ```python #python def linq7(): products = shared.getProductList() product_names = (p.ProductName for p in products) print("Product Names:") shared.printS(product_names) ``` #### Output Product Names: Chai Chang Aniseed Syrup Chef Anton's Cajun Seasoning Chef Anton's Gumbo Mix ... ### linq8: Select - Transformation >This sample projects a sequence of strings representing the text version of a sequence of integers. ```csharp //c# static void Linq8() { var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var strings = new [] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var textNums = numbers.Select(n => strings[n]); Console.WriteLine("Number strings:"); textNums.ForEach(Console.WriteLine); } ``` ```python #python def linq8(): numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0] strings = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] text_nums = (strings[n] for n in numbers) print("Number strings:") shared.printS(text_nums) ``` #### Output Number strings: five four one three nine eight six seven two zero ### linq9: Select - Anonymous Types 1 >"This sample projects a sequence of the uppercase and lowercase versions of each word in the original array. ```csharp //c# static void Linq9() { var words = new[] { "aPPLE", "BlUeBeRrY", "cHeRry" }; var upperLowerWords = words.Select(w => new { Upper = w.ToUpper(), Lower = w.ToLower() }); upperLowerWords.ForEach(ul => Console.WriteLine($"Uppercase: {ul.Upper}, Lowercase: {ul.Lower}")); } ``` ```python #python def linq9(): words = ["aPPLE", "BlUeBeRrY", "cHeRry"] upper_lower_words = (SimpleNamespace(Upper=w.upper(), Lower=w.lower()) for w in words) for word in upper_lower_words: print("Uppercase: %s, Lowercase: %s" % (word.Upper, word.Lower)) ``` #### Output Uppercase: APPLE, Lowercase: apple Uppercase: BLUEBERRY, Lowercase: blueberry Uppercase: CHERRY, Lowercase: cherry ### linq10: Select - Anonymous Types 2 >This sample projects a sequence containing text representations of digits and whether their length is even or odd. ```csharp //c# static void Linq10() { var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var digitOddEvens = numbers.Select(n => new { Digit = strings[n], Even = (n % 2 == 0) }); digitOddEvens.ForEach(d => Console.WriteLine($"The digit {d.Digit} is {(d.Even ? "even" : "odd")}.")); } ``` ```python #python def linq10(): numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0] strings = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] digit_odd_evens = (SimpleNamespace(Digit=strings[n], Even=(n % 2 == 0)) for n in numbers) for d in digit_odd_evens: print("The digit %s is %s" % (d.Digit, 'even' if d.Even else 'odd')) ``` #### Output The digit five is odd. The digit four is even. The digit one is odd. The digit three is odd. The digit nine is odd. The digit eight is even. The digit six is even. The digit seven is odd. The digit two is even. The digit zero is even. ### linq11: Select - Anonymous Types 3 >This sample projects a sequence containing some properties of Products, including UnitPrice which is renamed to Price in the resulting type. ```csharp //c# static void Linq11() { var products = GetProductList(); var productInfos = products.Select(p => new { p.ProductName, p.Category, Price = p.UnitPrice }); Console.WriteLine("Product Info:"); productInfos.ForEach(productInfo => Console.WriteLine($"{productInfo.ProductName} is in the category {productInfo.Category} and costs {productInfo.Price} per unit.")); } ``` ```python #python def linq11(): products = shared.getProductList() product_info = (SimpleNamespace(ProductName=p.ProductName, Category=p.Category, Price=p.UnitPrice) for p in products) print("Product Info:") for product in product_info: print("%s is in the category %s and costs %.2f per unit." % (product.ProductName, product.Category, product.Price)) ``` #### Output Product Info: Chai is in the category Beverages and costs 18.0 per unit. Chang is in the category Beverages and costs 19.0 per unit. Aniseed Syrup is in the category Condiments and costs 10.0 per unit. ... ### linq12: Select - Indexed >This sample uses an indexed projection to determine if the value of integers in an array match their position in the array. ```csharp //c# static void Linq12() { var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) }); Console.WriteLine("Number: In-place?"); numsInPlace.ForEach(n => Console.WriteLine($"{n.Num}: {n.InPlace}")); } ``` ```python #python def linq12(): numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0] index = 0 def digit_equals_index(digit): nonlocal index result = digit == index index += 1 return result nums_in_place = (SimpleNamespace(Num=num, InPlace=digit_equals_index(num)) for num in numbers) print("Number: In-place?") for n in nums_in_place: print("%d: %s" % (n.Num, n.InPlace)) ``` #### Output Number: In-place? 5: False 4: False 1: False 3: True 9: False 8: False 6: T ... ...

近期下载者

相关文件


收藏者