Trzy ciekawe funkcje Pythona
-
jacek
30/03/2020
- Programowanie
- 2964 czytań 0 komentarzy
- Top 3 Python Functions You Don’t Know About (Probably)
- Python | Ściągnięcie oraz instalacja | Czym jest język programowania?
#! /usr/bin/python3
#-*- coding: utf8 -*-
"""
Poniższe przykłady pokazują działanie trzech funkcji
które można zastąpić innym rozwiązaniem z iteracją
ale tak sa ładniejsze i działaja szybciej
"""
# Python program pokazuje pracę
# funkcji map
# n + n
def addition(n):
return n + n
# podwajamy wszystkie liczby za pomocą map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print("Wynik działania map",list(result))
# funkcja filter()
def wiecej_niz_15(x):
return x > 15
dane = [1,2,3,11,14,15,17,19,21,23,25,46,77,99]
print("Winik działania filter",list(filter(wiecej_niz_15,dane)))
# reduce()
"""
Oto logika:
5 dodaje się do 10, wyniki w 15
15 dodaje się do 12, wyniki w 27
27 zostaje dodane do 18, wyniki w 45
45 dodaje się do 25, wyniki w 70
"""
from functools import reduce
def dodaj_liczby(a,b):
return a + b
dane = [5,10,12,18,25]
print("Wynik działania reduce + :",reduce(dodaj_liczby,dane))
def pomnoz_liczby(a,b):
return a * b
dane = [5,10,12,18,25]
print("Wynik działania reduce * :",reduce(pomnoz_liczby,dane))
# List of strings
l = ['sat', 'bat', 'cat', 'mat']
# map() can listify the list of strings individually
test = list(map(list, l))
print(test)
# Add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))
# Double all numbers using map and lambda
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
# Python code to illustrate
# filter() with lambda()
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)
# Python code to illustrate
# map() with lambda()
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2 , li))
print(final_list)
# Python code to illustrate
# reduce() with lambda()
# to get sum of a list
li = [5,8,10,20,50,100]
suma = reduce((lambda x, y: x + y),li)
print(suma)
# Python code to demonstrate the working of
# sum()
numbers = [2.5, 3, 4, -5]
# sumujemy liczby
numbers_sum = sum(numbers)
print(numbers_sum)
# dodajemy 10
numbers_sum = sum(numbers, 10)
print(numbers_sum)
Przeczytaj więcej:
Dodaj komentarz
Zaloguj się, aby móc dodać komentarz.
Oceny
Tylko zarejestrowani użytkownicy mogą oceniać zawartość strony
Zaloguj się , żeby móc zagłosować.
Zaloguj się , żeby móc zagłosować.
Brak ocen. Może czas dodać swoją?



















































