Regex

Regex

Regular expressions provide a declarative language to match patterns within strings. They are commonly used for string validation, parsing, and transformation. Since regular expressions are not fully standardized, all questions with this tag should also include a tag specifying the applicable programming language or tool.
Duong Tran

Duong Tran

1679156346

3 cách sử dụng RegEx bên trong Lambda Function trong Python

Hướng dẫn Python RegEx này sẽ chỉ cho bạn 3 cách để sử dụng RegEx bên trong một hàm lambda trong Python bằng cách sử dụng các hàm filter(), map() và phương thức sort().

Có thể sử dụng RegEx bên trong hàm lambda trong Python. Bạn có thể áp dụng điều này cho bất kỳ phương thức hoặc hàm Python nào lấy một hàm làm tham số. Các hàm và phương thức như vậy bao gồm filter(), map(), any(), sort(), v.v.

Hãy tiếp tục đọc khi tôi chỉ cho bạn cách sử dụng các biểu thức chính quy bên trong hàm lambda.

Những gì chúng tôi sẽ bao gồm

  • Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda
    • Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda với Hàm filter()
    • Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda với Hàm map()
    • Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda với Phương thức sort()
  • Phần kết luận

Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda

Cú pháp mà hàm lambda có thể lấy RegEx làm biểu thức của nó trông như sau:

lambda x: re.method(pattern, x)

Xin lưu ý rằng bạn phải sử dụng hàm lambda trên một cái gì đó. Và đó là nơi những thứ như map(), sort(), filter(), và những thứ khác xuất hiện.

Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda với filter()Hàm

Ví dụ đầu tiên tôi sẽ chỉ cho bạn sử dụng filter()hàm:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

Trong đoạn mã trên:

  • cái filter()lấy hàm lambda làm hàm để thực thi và fruitsdanh sách làm hàm có thể lặp lại
  • đối với biểu thức của hàm lambda, nó sử dụng re.match()phương thức RegEx của Python và sử dụng mẫu ^atrên đối sốfruit
  • điều cuối cùng tôi làm là chuyển đổi tất cả các mục trong danh sách khớp với mẫu thành danh sách

Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda với map()Hàm

Để sử dụng RegEx bên trong hàm lambda với một hàm khác như map(), cú pháp tương tự:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

Trong đoạn mã trên:

  • đang modified_fruitslặp qua fruits2danh sách với một map()chức năng
  • sử dụng re.sub()phương thức RegEx của Python làm biểu thức của hàm lambda.

Phương pháp này re.subcho phép bạn thay thế giá trị đầu tiên bằng giá trị thứ hai. Trong ví dụ này, nó đã chuyển tất cả các lần xuất hiện của othành a.

Cách sử dụng RegEx bên trong Biểu thức của Hàm Lambda với sort()Phương thức

Ví dụ cuối cùng tôi sẽ chỉ cho bạn sử dụng sort()phương pháp danh sách:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

Trong mã, hàm lambda sắp xếp danh sách dựa trên số nguyên âm. Nó thực hiện điều đó với sự kết hợp của len()phương thức, findall()phương thức của Python RegEx và mẫu [aeiou].

Từ trái cây có ít nguyên âm nhất đứng đầu. Nếu bạn sử dụng reverse=True, nó sẽ sắp xếp các loại trái cây dựa trên những loại có số lượng nguyên âm cao nhất – thứ tự giảm dần:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

Phần kết luận

Trong bài viết này, chúng tôi đã xem xét cách bạn có thể chuyển RegEx sang hàm lambda bằng cách hiển thị cho bạn các ví dụ sử dụng hàm filter(), map()sort()phương thức.

Tôi hy vọng bài viết này cung cấp cho bạn kiến ​​thức cần thiết để sử dụng RegEx bên trong hàm lambda.

Tiếp tục viết mã!

Nguồn: https://www.freecodecamp.org

#python #regex 

3 cách sử dụng RegEx bên trong Lambda Function trong Python

3 طرق لاستخدام RegEx داخل دالة Lambda في Python

سيوضح لك هذا البرنامج التعليمي Python RegEx (التعبيرات العادية) 3 طرق لاستخدام RegEx داخل دالة lambda في Python باستخدام عامل التصفية () ووظائف الخريطة () وطريقة الفرز ().

من الممكن استخدام RegEx داخل دالة lambda في Python. يمكنك تطبيق هذا على أي طريقة أو وظيفة في Python تأخذ وظيفة كمعامل. تتضمن هذه الوظائف والأساليب عامل التصفية () والخريطة () وأي () والفرز () والمزيد.

استمر في القراءة حيث أوضح لك كيفية استخدام التعبيرات العادية داخل دالة لامدا.

ما سنقوم بتغطيته

  • كيفية استخدام RegEx داخل تعبير دالة Lambda
    • كيفية استخدام RegEx داخل التعبير عن دالة Lambda مع وظيفة المرشح ()
    • كيفية استخدام RegEx داخل التعبير عن دالة Lambda مع وظيفة map ()
    • كيفية استخدام RegEx داخل التعبير عن دالة Lambda باستخدام طريقة الفرز ()
  • خاتمة

كيفية استخدام RegEx داخل تعبير دالة Lambda

الصيغة التي يمكن أن تأخذ بها دالة lambda RegEx لأن تعبيرها يبدو كما يلي:

lambda x: re.method(pattern, x)

اعلم أنه يجب عليك استخدام وظيفة lambda في شيء ما. وهنا يأتي دور أمثال map()، sort()، filter()وآخرين.

كيفية استخدام RegEx داخل التعبير عن دالة Lambda مع filter()الوظيفة

المثال الأول الذي سأوضحه لك باستخدام الوظيفة filter():

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

في الكود أعلاه:

  • تأخذ filter()الدالة lambda كوظيفة يتم تنفيذها والقائمة fruitsباعتبارها وظيفة قابلة للتكرار
  • للتعبير عن دالة lambda ، تستخدم re.match()طريقة Python RegEx وتستخدم النمط ^aالموجود في الوسيطةfruit
  • آخر شيء فعلته هو تحويل جميع العناصر الموجودة في القائمة التي تتطابق مع النمط إلى قائمة

كيفية استخدام RegEx داخل التعبير عن دالة Lambda مع map()الوظيفة

لاستخدام RegEx داخل دالة lambda مع وظيفة أخرى مثل map()، يكون بناء الجملة مشابهًا:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

في الكود أعلاه:

  • يتكرر modified_fruitsعبر fruits2القائمة مع map()وظيفة
  • يستخدم re.sub()طريقة Python RegEx كتعبير عن وظيفة lambda.

تتيح لك الطريقة re.subاستبدال القيمة الأولى بالقيمة الثانية. في المثال ، حولت جميع تكرارات oإلى a.

كيفية استخدام RegEx داخل التعبير عن دالة Lambda مع sort()الطريقة

المثال الأخير الذي سأعرضه لكم يستخدم sort()طريقة القوائم:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

في الكود ، تقوم دالة lambda بفرز القائمة بناءً على عدد أحرف العلة. يقوم بذلك باستخدام مزيج من len()الطريقة وطريقة findall()Python RegEx والنمط [aeiou].

تأتي كلمة فاكهة التي تحتوي على أقل عدد من أحرف العلة أولاً. إذا كنت تستخدم reverse=True، فإنه يرتب الثمار بناءً على تلك التي تحتوي على أكبر عدد من أحرف العلة - ترتيب تنازلي:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

خاتمة

في هذه المقالة ، نظرنا في كيفية تمرير RegEx إلى دالة lambda من خلال عرض أمثلة لك باستخدام الدالة filter()، map()والوظائف ، والطريقة sort().

آمل أن تعطيك هذه المقالة المعرفة التي تحتاجها لاستخدام RegEx داخل وظيفة lambda.

استمر في الترميز!

المصدر: https://www.freecodecamp.org

#python #regex 

3 طرق لاستخدام RegEx داخل دالة Lambda في Python

3 maneiras de usar RegEx dentro de uma função Lambda em Python

Este tutorial Python RegEx (expressões regulares) mostrará 3 maneiras de usar RegEx dentro de uma função lambda em Python usando as funções filter(), map() e o método sort().

É possível usar RegEx dentro de uma função lambda em Python. Você pode aplicar isso a qualquer método ou função Python que receba uma função como parâmetro. Tais funções e métodos incluem filter(), map(), any(), sort() e muito mais.

Continue lendo enquanto mostro como usar expressões regulares dentro de uma função lambda.

O que abordaremos

  • Como usar o RegEx dentro da expressão de uma função Lambda
    • Como usar o RegEx dentro da expressão de uma função Lambda com a função filter()
    • Como usar o RegEx dentro da expressão de uma função Lambda com a função map()
    • Como usar RegEx dentro da Expressão de uma Função Lambda com o Método sort()
  • Conclusão

Como usar o RegEx dentro da expressão de uma função Lambda

A sintaxe com a qual uma função lambda pode receber um RegEx como sua expressão se parece com isto:

lambda x: re.method(pattern, x)

Esteja ciente de que você deve usar a função lambda em algo. E é aí que entram os gostos de map(), sort(), e outros.filter()

Como usar o RegEx dentro da Expressão de uma Função Lambda com a filter()Função

O primeiro exemplo que vou mostrar para você usa a filter()função:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

No código acima:

  • o filter()leva a função lambda como a função a ser executada e a fruitslista como o iterável
  • para a expressão da função lambda, usa o re.match()método do Python RegEx e usa o padrão ^ano argumentofruit
  • a última coisa que fiz foi converter todos os itens da lista que correspondem ao padrão em uma lista

Como usar o RegEx dentro da Expressão de uma Função Lambda com a map()Função

Para usar RegEx dentro de uma função lambda com outra função como map(), a sintaxe é semelhante:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

No código acima:

  • o modified_fruitsestá percorrendo a fruits2lista com uma map()função
  • usa o re.sub()método do Python RegEx como a expressão da função lambda.

O re.submétodo permite substituir o primeiro valor pelo segundo. No exemplo, trocou todas as ocorrências de opara a.

Como usar o RegEx dentro da Expressão de uma Função Lambda com o sort()Método

O último exemplo que mostrarei usa o sort()método de listas:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

No código, a função lambda classifica a lista com base no número de vogais. Ele faz isso com a combinação do len()método, o findall()método do Python RegEx e o padrão [aeiou].

A palavra fruta com o menor número de vogais vem primeiro. Se você usar reverse=True, ele organiza as frutas com base naquelas com maior número de vogais – ordem decrescente:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

Conclusão

Neste artigo, vimos como você pode passar RegEx para uma função lambda mostrando exemplos usando as filter()funções map(), e o sort()método.

Espero que este artigo forneça o conhecimento necessário para usar o RegEx dentro de uma função lambda.

Continue codificando!

Fonte: https://www.freecodecamp.org

#python #regex 

3 maneiras de usar RegEx dentro de uma função Lambda em Python
최  호민

최 호민

1679141717

Python의 Lambda 함수 내에서 RegEx를 사용하는 3가지 방법

이 Python RegEx(정규식) 자습서에서는 filter(), map() 함수 및 sort() 메서드를 사용하여 Python의 람다 함수 내에서 RegEx를 사용하는 3가지 방법을 보여줍니다.

Python의 람다 함수 내에서 RegEx를 사용할 수 있습니다. 함수를 매개 변수로 사용하는 모든 Python 메서드 또는 함수에 이를 적용할 수 있습니다. 이러한 함수 및 메서드에는 filter(), map(), any(), sort() 등이 포함됩니다.

람다 함수 내에서 정규식을 사용하는 방법을 보여주므로 계속 읽으십시오.

우리가 다룰 내용

  • Lambda 함수 표현식 내에서 RegEx를 사용하는 방법
    • filter() 함수와 함께 Lambda 함수의 표현식 내에서 RegEx를 사용하는 방법
    • map() 함수와 함께 Lambda 함수의 표현식 내에서 RegEx를 사용하는 방법
    • How to use RegEx inside the Expression of a Lambda Function with the sort() Method
  • Conclusion

How to use RegEx inside the Expression of a Lambda Function

The syntax with which a lambda function can take a RegEx as its expression looks like this:

lambda x: re.method(pattern, x)

Be aware that you have to use the lambda function on something. And that’s where the likes of map(), sort(), filter(), and others come in.

How to use RegEx inside the Expression of a Lambda Function with the filter() Function

The first example I will show you use the filter() function:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

In the code above:

  • the filter() takes the lambda function as the function to execute and the fruits list as the iterable
  • 람다 함수의 표현을 위해 Python RegEx의 방법을 사용 하고 인수에 re.match()패턴을 사용합니다.^afruit
  • 내가 한 마지막 작업은 패턴과 일치하는 목록의 모든 항목을 목록으로 변환하는 것입니다.

함수 가 있는 Lambda 함수의 표현식 내에서 RegEx를 사용하는 방법map()

와 같은 다른 함수가 있는 람다 함수 내에서 RegEx를 사용하려면 map()구문이 비슷합니다.

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

위의 코드에서:

  • 함수를 사용하여 목록을 반복 modified_fruits합니다.fruits2map()
  • re.sub()Python RegEx의 방법을 람다 함수의 표현으로 사용합니다 .

re.sub메서드를 사용하면 첫 번째 값을 두 번째 값으로 바꿀 수 있습니다. 이 예에서는 의 모든 발생을 o로 전환했습니다 a.

메서드를 사용하여 Lambda 함수의 표현식 내에서 RegEx를 사용하는 방법sort()

내가 보여줄 마지막 예는 sort()목록 방법을 사용합니다.

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

코드에서 람다 함수는 모음 수를 기준으로 목록을 정렬합니다. len()메소드, findall()Python RegEx의 메소드 및 패턴 의 조합으로 수행합니다 [aeiou].

모음 수가 가장 적은 과일이 먼저 나옵니다. 를 사용하면 reverse=True모음이 가장 많은 과일을 기준으로 내림차순으로 배열합니다.

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

결론

이 기사에서는 , 함수 및 메소드 를 사용하는 예제를 보여줌으로써 RegEx에서 람다 함수로 전달하는 방법을 살펴 filter()보았습니다 .map()sort()

이 기사가 람다 함수 내에서 RegEx를 사용하는 데 필요한 지식을 제공하기를 바랍니다.

계속 코딩하세요!

출처: https://www.freecodecamp.org

#python #regex 

Python의 Lambda 함수 내에서 RegEx를 사용하는 3가지 방법

3 способа использования RegEx внутри лямбда-функции в Python

В этом руководстве по Python RegEx (регулярные выражения) показаны 3 способа использования RegEx внутри лямбда-функции в Python с использованием функций filter(), map() и метода sort().

В Python можно использовать RegEx внутри лямбда-функции. Вы можете применить это к любому методу или функции Python, которая принимает функцию в качестве параметра. К таким функциям и методам относятся filter(), map(), any(), sort() и другие.

Продолжайте читать, пока я покажу вам, как использовать регулярные выражения внутри лямбда-функции.

Что мы рассмотрим

  • Как использовать RegEx внутри выражения лямбда-функции
    • Как использовать RegEx внутри выражения лямбда-функции с функцией filter()
    • Как использовать RegEx внутри выражения лямбда-функции с функцией map()
    • Как использовать RegEx внутри выражения лямбда-функции с помощью метода sort()
  • Заключение

Как использовать RegEx внутри выражения лямбда-функции

Синтаксис, с помощью которого лямбда-функция может принимать RegEx в качестве своего выражения, выглядит следующим образом:

lambda x: re.method(pattern, x)

Имейте в виду, что вам нужно использовать лямбда-функцию для чего-то. И вот тут-то и появляются такие map(), как sort(), , и другие.filter()

Как использовать RegEx внутри выражения лямбда-функции с filter()функцией

В первом примере я покажу вам использование filter()функции:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

В приведенном выше коде:

  • принимает filter()лямбда-функцию в качестве функции для выполнения и fruitsсписок в качестве итерируемого
  • для выражения лямбда-функции он использует re.match()метод Python RegEx и использует шаблон ^aдля аргументаfruit
  • Последнее, что я сделал, это преобразовал все элементы в списке, соответствующие шаблону, в список.

Как использовать RegEx внутри выражения лямбда-функции с map()функцией

Чтобы использовать RegEx внутри лямбда-функции с другой функцией, такой как map(), синтаксис аналогичен:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

В приведенном выше коде:

  • перебирает modified_fruitsсписок fruits2с помощью map()функции
  • использует re.sub()метод Python RegEx как выражение лямбда-функции.

Метод re.subпозволяет заменить первое значение вторым. В примере он переключил все вхождения oна a.

Как использовать RegEx внутри выражения лямбда-функции с sort()методом

В последнем примере, который я вам покажу, используется sort()метод списков:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

В коде лямбда-функция сортирует список по количеству гласных. Он делает это с помощью комбинации метода len(), findall()метода Python RegEx и шаблона [aeiou].

Первым идет слово фрукты с наименьшим количеством гласных. Если вы используете reverse=True, он упорядочивает плоды по количеству гласных в порядке убывания:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

Заключение

В этой статье мы рассмотрели, как вы можете передать RegEx в лямбда-функцию, показав вам примеры с использованием функций filter(), map()и sort()метода.

Я надеюсь, что эта статья даст вам знания, необходимые для использования RegEx внутри лямбда-функции.

Продолжайте кодировать!

Источник: https://www.freecodecamp.org

#python #regex 

3 способа использования RegEx внутри лямбда-функции в Python
曾 俊

曾 俊

1679134447

Python の Lambda 関数内で RegEx を使用する 3 つの方法

この Python RegEx (正規表現) チュートリアルでは、filter()、map() 関数、および sort() メソッドを使用して、Python のラムダ関数内で RegEx を使用する 3 つの方法を示します。

Python のラムダ関数内で RegEx を使用することは可能です。これは、関数をパラメーターとして受け取る任意の Python メソッドまたは関数に適用できます。このような関数とメソッドには、filter()、map()、any()、sort() などがあります。

ラムダ関数内で正規表現を使用する方法を説明するので、読み続けてください。

カバーする内容

  • Lambda 関数の式内で RegEx を使用する方法
    • filter() 関数を使用して Lambda 関数の式内で RegEx を使用する方法
    • map() 関数を使用して Lambda 関数の式内で RegEx を使用する方法
    • sort() メソッドを使用して Lambda 関数の式内で RegEx を使用する方法
  • 結論

Lambda 関数の式内で RegEx を使用する方法

ラムダ関数が正規表現を式として使用できる構文は、次のようになります。

lambda x: re.method(pattern, x)

何かでラムダ関数を使用する必要があることに注意してください。そして、そこにmap()sort()filter()、その他が登場します。

関数を使用して Lambda 関数の式内で RegEx を使用する方法filter()

関数を使用する最初の例を示しますfilter()

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

上記のコードでは:

  • これはfilter()ラムダ関数を実行する関数として取り、fruitsリストをイテラブルとして取ります
  • ラムダ関数の式には、Python RegEx のメソッドを使用し、引数にre.match()パターンを使用します^afruit
  • 私が最後にしたことは、パターンに一致するリスト上のすべてのアイテムをリストに変換することでした

関数を使用して Lambda 関数の式内で RegEx を使用する方法map()

のような別の関数でラムダ関数内で RegEx を使用するにはmap()、構文は似ています。

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

上記のコードでは:

  • 関数を使用してリストをループmodified_fruitsしていますfruits2map()
  • re.sub()ラムダ関数の式として Python RegEx のメソッドを使用します。

このre.subメソッドを使用すると、最初の値を 2 番目の値に置き換えることができます。この例では、出現するすべてのoを に切り替えましたa

メソッドを使用して Lambda 関数の式内で RegEx を使用する方法sort()

最後に紹介する例では、sort()リストの方法を使用しています。

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

コードでは、ラムダ関数が母音の数に基づいてリストを並べ替えます。len()メソッド、findall()Python RegEx のメソッド、および patternの組み合わせで行います[aeiou]

母音の数が最も少ない果物が最初に来ます。を使用するとreverse=True、母音の数が最も多いものに基づいてフルーツが降順で並べられます。

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

結論

filter()この記事では、 、 関数、map()メソッドを使用した例を示して、ラムダ関数に RegEx を渡す方法について説明しましたsort()

この記事で、ラムダ関数内で RegEx を使用するために必要な知識が得られることを願っています。

コーディングを続けてください!

ソース: https://www.freecodecamp.org

#python #regex 

Python の Lambda 関数内で RegEx を使用する 3 つの方法
Zachary Palmer

Zachary Palmer

1679130807

3 façons d'utiliser RegEx dans une fonction Lambda en Python

Ce tutoriel Python RegEx (Regular Expressions) vous montrera 3 façons d'utiliser RegEx dans une fonction lambda en Python en utilisant les fonctions filter(), map() et la méthode sort().

Il est possible d'utiliser RegEx dans une fonction lambda en Python. Vous pouvez l'appliquer à n'importe quelle méthode ou fonction Python qui prend une fonction comme paramètre. Ces fonctions et méthodes incluent filter(), map(), any(), sort(), etc.

Continuez à lire pendant que je vous montre comment utiliser des expressions régulières dans une fonction lambda.

Ce que nous couvrirons

  • Comment utiliser RegEx dans l'expression d'une fonction Lambda
    • Comment utiliser RegEx dans l'expression d'une fonction Lambda avec la fonction filter()
    • Comment utiliser RegEx dans l'expression d'une fonction Lambda avec la fonction map()
    • Comment utiliser RegEx dans l'expression d'une fonction Lambda avec la méthode sort()
  • Conclusion

Comment utiliser RegEx dans l'expression d'une fonction Lambda

La syntaxe avec laquelle une fonction lambda peut prendre un RegEx comme son expression ressemble à ceci :

lambda x: re.method(pattern, x)

Sachez que vous devez utiliser la fonction lambda sur quelque chose. Et c'est là que les goûts de map(), sort(), filter(), et d'autres entrent en jeu.

Comment utiliser RegEx dans l'expression d'une fonction Lambda avec la filter()fonction

Le premier exemple que je vais vous montrer utilise la filter()fonction :

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

Dans le code ci-dessus :

  • prend filter()la fonction lambda comme fonction à exécuter et la fruitsliste comme itérable
  • pour l'expression de la fonction lambda, il utilise la re.match()méthode de Python RegEx et utilise le motif ^asur l'argumentfruit
  • la dernière chose que j'ai faite a été de convertir tous les éléments de la liste qui correspondent au modèle en une liste

Comment utiliser RegEx dans l'expression d'une fonction Lambda avec la map()fonction

Pour utiliser RegEx dans une fonction lambda avec une autre fonction telle que map(), la syntaxe est similaire :

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

Dans le code ci-dessus :

  • le modified_fruitsparcourt la fruits2liste avec une map()fonction
  • utilise la re.sub()méthode de Python RegEx comme expression de la fonction lambda.

La re.subméthode vous permet de remplacer la première valeur par la seconde. Dans l'exemple, il a remplacé toutes les occurrences ode a.

Comment utiliser RegEx dans l'expression d'une fonction Lambda avec la sort()méthode

Le dernier exemple que je vais vous montrer utilise la sort()méthode des listes :

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

Dans le code, la fonction lambda trie la liste en fonction du nombre de voyelles. Il le fait avec la combinaison de la len()méthode, la findall()méthode de Python RegEx et le pattern [aeiou].

Le mot fruit avec le plus petit nombre de voyelles vient en premier. Si vous utilisez reverse=True, il organise les fruits en fonction de ceux qui ont le plus grand nombre de voyelles - ordre décroissant :

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

Conclusion

Dans cet article, nous avons examiné comment vous pouvez transmettre RegEx à une fonction lambda en vous montrant des exemples utilisant les filter()fonctions map(), et la sort()méthode .

J'espère que cet article vous donnera les connaissances dont vous avez besoin pour utiliser RegEx dans une fonction lambda.

Continuez à coder !

Source : https://www.freecodecamp.org

#python #regex 

3 façons d'utiliser RegEx dans une fonction Lambda en Python
Iara  Simões

Iara Simões

1679127180

3 formas de usar RegEx dentro de una función Lambda en Python

Este tutorial de Python RegEx (Expresiones regulares) le mostrará 3 formas de usar RegEx dentro de una función lambda en Python usando las funciones filter(), map() y sort().

Es posible usar RegEx dentro de una función lambda en Python. Puede aplicar esto a cualquier método o función de Python que tome una función como parámetro. Tales funciones y métodos incluyen filter(), map(), any(), sort() y más.

Siga leyendo mientras le muestro cómo usar expresiones regulares dentro de una función lambda.

Lo que cubriremos

  • Cómo usar RegEx dentro de la expresión de una función Lambda
    • Cómo usar RegEx dentro de la expresión de una función Lambda con la función filter()
    • Cómo usar RegEx dentro de la expresión de una función Lambda con la función map()
    • Cómo usar RegEx dentro de la expresión de una función Lambda con el método sort()
  • Conclusión

Cómo usar RegEx dentro de la expresión de una función Lambda

La sintaxis con la que una función lambda puede tomar un RegEx como su expresión se ve así:

lambda x: re.method(pattern, x)

Tenga en cuenta que tiene que usar la función lambda en algo. Y ahí es donde entran los gustos de map(), sort(), y otros.filter()

Cómo usar RegEx dentro de la expresión de una función Lambda con la filter()función

El primer ejemplo que te mostraré usa la filter()función:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

En el código de arriba:

  • toma filter()la función lambda como la función a ejecutar y la fruitslista como iterable
  • para la expresión de la función lambda, utiliza el re.match()método de Python RegEx y utiliza el patrón ^aen el argumentofruit
  • lo último que hice fue convertir todos los elementos de la lista que coinciden con el patrón en una lista

Cómo usar RegEx dentro de la expresión de una función Lambda con la map()función

Para usar RegEx dentro de una función lambda con otra función como map(), la sintaxis es similar:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

En el código de arriba:

  • el modified_fruitsestá recorriendo la fruits2lista con una map()función
  • utiliza el re.sub()método de Python RegEx como expresión de la función lambda.

El re.submétodo le permite reemplazar el primer valor con el segundo. En el ejemplo, cambió todas las apariciones de oa a.

Cómo usar RegEx dentro de la expresión de una función Lambda con el sort()método

El último ejemplo que les mostraré usa el sort()método de listas:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

En el código, la función lambda ordena la lista según el número de vocales. Lo hace con la combinación del len()método, el findall()método de Python RegEx y el patrón [aeiou].

La palabra fruta con el menor número de vocales va primero. Si usa reverse=True, organiza las frutas en función de las que tienen el mayor número de vocales, en orden descendente:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

Conclusión

En este artículo, analizamos cómo puede pasar RegEx a una función lambda mostrándole ejemplos usando las filter()funciones map(), y el sort()método.

Espero que este artículo le brinde el conocimiento que necesita para usar RegEx dentro de una función lambda.

¡Sigue codificando!

Fuente: https://www.freecodecamp.org

#python #regex 

3 formas de usar RegEx dentro de una función Lambda en Python

3 วิธีในการใช้ RegEx ภายในฟังก์ชัน Lambda ใน Python

บทช่วยสอน Python RegEx (Regular Expressions) นี้จะแสดงให้คุณเห็น 3 วิธีในการใช้ RegEx ภายในฟังก์ชัน lambda ใน Python โดยใช้ฟังก์ชัน filter(), map() และ sort()

เป็นไปได้ที่จะใช้ RegEx ภายในฟังก์ชันแลมบ์ดาใน Python คุณสามารถใช้วิธีนี้กับเมธอดหรือฟังก์ชัน Python ที่รับฟังก์ชันเป็นพารามิเตอร์ ฟังก์ชันและวิธีการดังกล่าวรวมถึง filter(), map(), any(), sort() และอื่นๆ

อ่านต่อในขณะที่ฉันแสดงวิธีใช้นิพจน์ทั่วไปภายในฟังก์ชันแลมบ์ดา

สิ่งที่เราจะครอบคลุม

  • วิธีใช้ RegEx ภายในนิพจน์ของฟังก์ชันแลมบ์ดา
    • วิธีใช้ RegEx ภายใน Expression ของฟังก์ชัน Lambda ด้วยฟังก์ชัน filter()
    • วิธีใช้ RegEx ภายในนิพจน์ของฟังก์ชันแลมบ์ดาด้วยฟังก์ชัน map()
    • วิธีใช้ RegEx ภายในนิพจน์ของฟังก์ชันแลมบ์ดาด้วยวิธี sort()
  • บทสรุป

วิธีใช้ RegEx ภายในนิพจน์ของฟังก์ชันแลมบ์ดา

ไวยากรณ์ที่ฟังก์ชันแลมบ์ดาสามารถใช้ RegEx ได้เนื่องจากนิพจน์มีลักษณะดังนี้:

lambda x: re.method(pattern, x)

โปรดทราบว่าคุณต้องใช้ฟังก์ชันแลมบ์ดากับบางสิ่ง และนั่นคือสิ่งที่ชอบของmap(), sort(), filter(), และอื่นๆ เข้ามา

วิธีใช้ RegEx ภายในนิพจน์ของฟังก์ชันแลมบ์ดาด้วยfilter()ฟังก์ชัน

ตัวอย่างแรกที่ฉันจะแสดงให้คุณใช้filter()ฟังก์ชัน:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

ในรหัสด้านบน:

  • ใช้filter()ฟังก์ชันแลมบ์ดาเป็นฟังก์ชันในการดำเนินการและfruitsรายการเป็นฟังก์ชันที่วนซ้ำได้
  • สำหรับนิพจน์ของฟังก์ชันแลมบ์ดาจะใช้re.match()เมธอดของ Python RegEx และใช้รูปแบบ^aในอาร์กิวเมนต์fruit
  • สิ่งสุดท้ายที่ฉันทำคือแปลงรายการทั้งหมดในรายการที่ตรงกับรูปแบบให้เป็นรายการ

วิธีใช้ RegEx ภายในนิพจน์ของฟังก์ชันแลมบ์ดาด้วยmap()ฟังก์ชัน

หากต้องการใช้ RegEx ภายในฟังก์ชันแลมบ์ดากับฟังก์ชันอื่น เช่นmap()ไวยากรณ์จะคล้ายกัน:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

ในรหัสด้านบน:

  • กำลังmodified_fruitsวนซ้ำผ่านfruits2รายการด้วยmap()ฟังก์ชัน
  • ใช้re.sub()วิธีการของ Python RegEx เป็นนิพจน์ของฟังก์ชันแลมบ์ดา

วิธีการ นี้re.subให้คุณแทนที่ค่าแรกด้วยค่าที่สอง ในตัวอย่าง จะสลับเหตุการณ์ทั้งหมดoเป็นa

วิธีใช้ RegEx ภายในนิพจน์ของฟังก์ชันแลมบ์ดาด้วยsort()เมธอด

ตัวอย่างสุดท้ายที่ฉันจะแสดงให้คุณเห็นโดยใช้sort()เมธอดของรายการ:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

ในโค้ด ฟังก์ชันแลมบ์ดาจะเรียงลำดับรายการตามจำนวนสระ มันทำด้วยการรวมกันของlen()วิธีการfindall()วิธีการของ Python RegEx และรูป[aeiou]แบบ

ผลไม้ คำที่มีจำนวนสระน้อยที่สุดมาก่อน หากคุณใช้reverse=Trueจะจัดเรียงผลไม้ตามจำนวนสระที่มีจำนวนสระมากที่สุด - เรียงลำดับจากมากไปน้อย:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

บทสรุป

ในบทความนี้ เราได้ดูวิธีที่คุณสามารถส่งผ่าน RegEx ไปยังฟังก์ชันแลมบ์ดาโดยแสดงตัวอย่างโดยใช้filter()ฟังก์ชันmap()และsort()เมธอด

ฉันหวังว่าบทความนี้จะให้ความรู้ที่จำเป็นในการใช้ RegEx ในฟังก์ชันแลมบ์ดา

เขียนโค้ดต่อไป!

ที่มา: https://www.freecodecamp.org

#python #regex 

3 วิธีในการใช้ RegEx ภายในฟังก์ชัน Lambda ใน Python
许 志强

许 志强

1679119920

在 Python 中的 Lambda 函數中使用 RegEx 的 3 種方法

本 Python RegEx(正則表達式)教程將向您展示 3 種在 Python 中使用 filter()、map() 函數和 sort() 方法在 lambda 函數中使用 RegEx 的方法。

可以在 Python 的 lambda 函數中使用 RegEx。您可以將其應用於任何將函數作為參數的 Python 方法或函數。此類函數和方法包括 filter()、map()、any()、sort() 等。

繼續閱讀我向您展示的如何在 lambda 函數中使用正則表達式。

我們將涵蓋的內容

  • 如何在 Lambda 函數的表達式中使用 RegEx
    • 如何在帶有 filter() 函數的 Lambda 函數表達式中使用 RegEx
    • 如何在帶有 map() 函數的 Lambda 函數表達式中使用 RegEx
    • 如何通過 sort() 方法在 Lambda 函數的表達式中使用 RegEx
  • 結論

如何在 Lambda 函數的表達式中使用 RegEx

lambda 函數可以採用 RegEx 作為其表達式的語法如下所示:

lambda x: re.method(pattern, x)

請注意,您必須對某些內容使用 lambda 函數。map()這就是、sort()filter()和其他人的用武之地。

如何在帶有函數的Lambda 函數表達式中使用 RegExfilter()

我將向您展示的第一個示例使用該filter()函數:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

在上面的代碼中:

  • filter()lambda 函數作為要執行的函數,將fruits列表作為可迭代對象
  • for the expression of the lambda function, it uses the re.match() method of Python RegEx and uses the pattern ^a on the argument fruit
  • the last thing I did was convert all items on the list that matches the pattern into a list

How to use RegEx inside the Expression of a Lambda Function with the map() Function

To use RegEx inside a lambda function with another function like map(), the syntax is similar:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

In the code above:

  • the modified_fruits is looping through the fruits2 list with a map() function
  • uses the re.sub() method of Python RegEx as the expression of the lambda function.

The re.sub method lets you replace the first value with the second one. In the example, it switched all occurrences of o to a.

如何使用方法在 Lambda 函數的表達式中使用 RegExsort()

我將向您展示的最後一個示例使用sort()列表方法:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

在代碼中,lambda 函數根據元音的數量對列表進行排序。它結合方法len()findall()Python RegEx 的方法和模式來實現[aeiou]

元音數量最少的單詞 fruit 排在最前面。如果您使用reverse=True,它會根據元音數量最多的水果排列水果 - 降序:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

結論

filter()在本文中,我們通過向您展示使用、map()函數和方法的示例,研究瞭如何將 RegEx 傳遞給 lambda 函數sort()

我希望本文能為您提供在 lambda 函數中使用 RegEx 所需的知識。

繼續編碼!

資料來源: https: //www.freecodecamp.org

#python #regex 

在 Python 中的 Lambda 函數中使用 RegEx 的 3 種方法
Romolo  Morelli

Romolo Morelli

1679116260

3 modi per utilizzare RegEx all'interno di una funzione Lambda in Python

Questo tutorial Python RegEx (Regular Expressions) ti mostrerà 3 modi per usare RegEx all'interno di una funzione lambda in Python usando le funzioni filter(), map() e il metodo sort().

È possibile utilizzare RegEx all'interno di una funzione lambda in Python. Puoi applicarlo a qualsiasi metodo o funzione Python che accetta una funzione come parametro. Tali funzioni e metodi includono filter(), map(), any(), sort() e altro.

Continua a leggere mentre ti mostro come usare le espressioni regolari all'interno di una funzione lambda.

Di cosa parleremo

  • Come utilizzare RegEx all'interno dell'espressione di una funzione Lambda
    • Come utilizzare RegEx all'interno dell'espressione di una funzione Lambda con la funzione filter()
    • Come utilizzare RegEx all'interno dell'espressione di una funzione Lambda con la funzione map()
    • Come utilizzare RegEx all'interno dell'espressione di una funzione Lambda con il metodo sort()
  • Conclusione

Come utilizzare RegEx all'interno dell'espressione di una funzione Lambda

La sintassi con cui una funzione lambda può assumere una RegEx come sua espressione è la seguente:

lambda x: re.method(pattern, x)

Tieni presente che devi usare la funzione lambda su qualcosa. Ed è qui che entrano in gioco artisti del calibro di map(), sort(), filter()e altri.

Come utilizzare RegEx all'interno dell'espressione di una funzione lambda con la filter()funzione

Il primo esempio che ti mostrerò usa la filter()funzione:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

Nel codice sopra:

  • prende filter()la funzione lambda come funzione da eseguire e l' fruitselenco come iterabile
  • per l'espressione della funzione lambda, usa il re.match()metodo di Python RegEx e usa il pattern ^asull'argomentofruit
  • l'ultima cosa che ho fatto è stata convertire tutti gli elementi dell'elenco che corrispondono allo schema in un elenco

Come utilizzare RegEx all'interno dell'espressione di una funzione lambda con la map()funzione

Per utilizzare RegEx all'interno di una funzione lambda con un'altra funzione come map(), la sintassi è simile:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

Nel codice sopra:

  • sta modified_fruitsscorrendo l' fruits2elenco con una map()funzione
  • utilizza il re.sub()metodo di Python RegEx come espressione della funzione lambda.

Il re.submetodo consente di sostituire il primo valore con il secondo. Nell'esempio, ha cambiato tutte le occorrenze di oin a.

Come utilizzare RegEx all'interno dell'espressione di una funzione Lambda con il sort()metodo

L'ultimo esempio che ti mostrerò utilizza il sort()metodo delle liste:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

Nel codice, la funzione lambda ordina l'elenco in base al numero di vocali. Lo fa con la combinazione del len()metodo, il findall()metodo di Python RegEx e il pattern [aeiou].

La parola frutto con il minor numero di vocali viene prima. Se usi reverse=True, dispone i frutti in base a quelli con il maggior numero di vocali – ordine decrescente:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

Conclusione

In questo articolo, abbiamo esaminato come passare RegEx a una funzione lambda mostrandoti esempi utilizzando le filter()funzioni map(), e il sort()metodo.

Spero che questo articolo ti fornisca le conoscenze necessarie per utilizzare RegEx all'interno di una funzione lambda.

Continua a programmare!

Fonte: https://www.freecodecamp.org

#python #regex 

3 modi per utilizzare RegEx all'interno di una funzione Lambda in Python
Dylan  Iqbal

Dylan Iqbal

1679112030

3 Ways to Use RegEx Inside a Lambda Function in Python

This Python RegEx (Regular Expressions) tutorial will show you 3 ways to use RegEx inside a lambda function in Python using the filter(), map() functions, and the sort() method.

It’s possible to use RegEx inside a lambda function in Python. You can apply this to any Python method or function that takes a function as a parameter. Such functions and methods include filter(), map(), any(), sort(), and more.

Keep reading as I show you how to use regular expressions inside a lambda function.

What We'll Cover

  • How to use RegEx inside the Expression of a Lambda Function
    • How to use RegEx inside the Expression of a Lambda Function with the filter() Function
    • How to use RegEx inside the Expression of a Lambda Function with the map() Function
    • How to use RegEx inside the Expression of a Lambda Function with the sort() Method
  • Conclusion

How to use RegEx inside the Expression of a Lambda Function

The syntax with which a lambda function can take a RegEx as its expression looks like this:

lambda x: re.method(pattern, x)

Be aware that you have to use the lambda function on something. And that’s where the likes of map(), sort(), filter(), and others come in.

How to use RegEx inside the Expression of a Lambda Function with the filter() Function

The first example I will show you use the filter() function:

import re

fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)

# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']

In the code above:

  • the filter() takes the lambda function as the function to execute and the fruits list as the iterable
  • for the expression of the lambda function, it uses the re.match() method of Python RegEx and uses the pattern ^a on the argument fruit
  • the last thing I did was convert all items on the list that matches the pattern into a list

How to use RegEx inside the Expression of a Lambda Function with the map() Function

To use RegEx inside a lambda function with another function like map(), the syntax is similar:

import re

fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)

# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']

In the code above:

  • the modified_fruits is looping through the fruits2 list with a map() function
  • uses the re.sub() method of Python RegEx as the expression of the lambda function.

The re.sub method lets you replace the first value with the second one. In the example, it switched all occurrences of o to a.

How to use RegEx inside the Expression of a Lambda Function with the sort() Method

The last example I will show you uses the sort() method of lists:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))

print(fruits) #['fig', 'banana', 'grapefruit']

In the code, the lambda function sorts the list based on the number of vowels. It does it with the combination of the len() method, the findall() method of Python RegEx, and the pattern [aeiou].

The word fruit with the lowest number of vowels comes first. If you use reverse=True, it arranges the fruits based on those with the highest number of vowels – descending order:

import re

fruits = [ 'banana', 'fig', 'grapefruit']

# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)

print(fruits) # ['grapefruit', 'banana', 'fig']

Conclusion

In this article, we looked at how you can pass in RegEx to a lambda function by showing you examples using the filter(), map() functions, and the sort() method.

I hope this article gives you the knowledge you need to use RegEx inside a lambda function.

Keep coding!

Source: https://www.freecodecamp.org

#python #regex 

3 Ways to Use RegEx Inside a Lambda Function in Python
Rakesh Sharma

Rakesh Sharma

1679068206

JavaScript Regex Tutorial Zero to Hero

JavaScript regular expressions, also known as regex, are powerful tools for working with text. They allow you to search, replace, and manipulate text based on patterns.

#JavaScript #regex 

JavaScript Regex Tutorial Zero to Hero
Romolo  Morelli

Romolo Morelli

1677769740

Come importare un'espressione regolare in Python

In questo tutorial su Python RegEx (Regular Expression), imparerai come importare espressioni regolari in Python e usarle. Utilizzo del modulo con i metodi per lavorare con le espressioni regolari in Python.

Praticamente tutti i linguaggi di programmazione là fuori supportano le espressioni regolari. Regex è integrato in linguaggi come JavaScript e Pearl, mentre altri come Java e Python hanno librerie standard per lavorarci.

In questo articolo vedremo come importare espressioni regolari in Python e utilizzarle. Vedremo anche alcuni metodi forniti da Python per lavorare con le espressioni regolari.

Sommario:

  • Come importare espressioni regolari in Python
  • Come utilizzare il remodulo Python con RegEx
    • Esempio RegEx con il match()metodo
    • Esempio RegEx con il search()metodo
    • Esempio RegEx con il findall()metodo
    • Esempio RegEx con il split()metodo
    • Esempio RegEx con il sub()metodo
  • Conclusione

Come importare espressioni regolari in Python

Python fornisce il remodulo per usare le espressioni regolari. È un modulo standard integrato in Python, quindi se hai l'ultima versione di Python, non è necessario installarlo separatamente con i gestori di pacchetti.

Per importare il remodulo in Python, lo fai con la parola chiave import:

import re

Come utilizzare il remodulo Python con RegEx

Python fornisce alcuni metodi che puoi usare per lavorare con espressioni regolari come match(), search(), findall(), split()e sub().

Per usare questi metodi con RegEx, devi farli precedere dal remodulo e dal punto ( .) in questo modo:

re.match(pattern, string) # to use the match method
re.findall(pattern, string) # to use the findall method 
re.sub(pattern, string) # to use the sub method
re.search(pattern, string) # to use the search method 
re.split(pattern, string) # to use the split method

Gli esempi RegEx che ho fornito utilizzeranno questi metodi.

Esempio di RegEx utilizzando il match()metodo

Il match()prende un'espressione regolare e la stringa e quindi controlla se la stringa corrisponde al modello nell'espressione regolare.

Ecco un esempio:

import re 

my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'

res = re.match(my_regex_1, my_txt)
print(res) # returns None

Nell'esempio sopra:

  • Ho una my_txtvariabile impostata su freeCodeCampe una my_regex_1variabile impostata su pattern ^freecodecamp$. È così che scrivi le espressioni regolari in Python: le metti tra virgolette.
  • Per verificare se il testo corrisponde al modello, ho utilizzato il match()metodo e inserito le variabili my_regex_1e my_txt.

La stringa è freeCodeCamp, e lo schema è ^freecodecamp$, quindi perché il metodo match ha restituito None? È perché non trova una corrispondenza.

Ci sono alcune lettere maiuscole nella my_txtvariabile, ma il modello cerca lettere minuscole.

Se hai familiarità con RegEx in JavaScript o Pearl, puoi utilizzare il iflag per abbinare tutte le lettere maiuscole o minuscole in una stringa.

Quindi, quello che dobbiamo fare per avere una corrispondenza è usare la ibandiera. Ma usare un flag con espressioni regolari in Python è diverso da come lo usiamo in JavaScript.

Per utilizzare i flag con le espressioni regolari in Python, il remodulo fornisce le opzioni IGNORECASE, ASCII, MULTILINE, VERBOSE, DOTALLe .LOCAL

Ecco come useresti un flag con espressioni regolari in Python:

re.match(pattern, string, re.ASCII) # to perform only ASCII matching 
re.findall(pattern, string, re.DOTALL) # to match any character – including a new line.
re.sub(pattern, string, re.IGNORECASE) # to perform case insensitive matching
re.search(pattern, string, re.LOCALE) # to perform case insensitive matching dependent on the current locale
re.search(pattern, string, re.VERBOSE) # to allow comments in regex
re.split(pattern, string, re.MULTILINE) # to perform multiple line matching. Commonly used with metacharacters (^ and $)

Per il nostro esempio, il flag che possiamo usare è il IGNORECASE. Usiamolo in modo da poter ottenere una corrispondenza:

import re 

my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'

res = re.match(my_regex_1, my_txt, re.IGNORECASE)
print(res) #Output: <re.Match object; span=(0, 12), match='freeCodeCamp'>

Ora abbiamo una partita!

Esempio di RegEx utilizzando il search()metodo

La search()funzione accetta una regex e una stringa e quindi restituisce la prima occorrenza in un oggetto match. Se non trova alcuna corrispondenza, restituisce None.

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

res = re.search(my_regex, my_txt, re.IGNORECASE)
print(res) # <re.Match object; span=(6, 12), match='Friday'>

Puoi vedere che restituisce la prima occorrenza del testo Friday, situata tra index 6e 12.

Puoi ottenere quell'indice con il start()metodo:

res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located at index ", res.start()) # The first occurrence is located at index  6

Puoi ottenere l'indice iniziale e finale dell'occorrenza in questo modo:

res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located between index", res.start(), "and index", res.end()) # The first occurrence is located between index 6 and index 12

Puoi anche usare match()con una if…elsedichiarazione:

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

if re.search(my_regex, my_txt, re.IGNORECASE):
    print("Found a match!") #Output: Found a match!
else:
    print("Found no match")   
res = re.search(my_regex, my_txt, re.IGNORECASE)

Esempio di RegEx utilizzando il findall()metodo

Il findall()metodo accetta una regex e una stringa, quindi esamina la stringa e trova tutte le occorrenze che corrispondono alla regex. Mette tutte quelle occorrenze all'interno di un elenco.

Ecco un esempio:

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'
res = re.findall(my_regex, my_txt, re.IGNORECASE)

print(res) # Output: ['Friday', 'Friday', 'Friday', 'Friday']

Si noti che l'espressione regolare che uso contiene il testo friday, che non corrisponde a nessuna occorrenza di "venerdì". La IGNORECASEbandiera era ciò che la faceva corrispondere a quelle occorrenze.

Esempio di RegEx utilizzando il split()metodo

Il split()metodo fa ciò che implica il nome: divide una stringa in base al modello passato in essa.

Questo metodo potrebbe essere utile se vuoi filtrare alcune parole che non vuoi in una stringa.

import re 

my_txt = "Python and JavaScript and C# and Java and Golang and F#"
my_regex = 'and'

res = re.split(my_regex, my_txt)
print(res) # ['Python ', ' JavaScript ', ' C# ', ' Java ', ' Golang ', ' F#']

Esempio di RegEx utilizzando il sub()metodo

Funziona sub()come il metodo di JavaScript replace(). Sostituisce il carattere che corrisponde all'espressione regolare che gli è stata passata.

Il sub()metodo è leggermente diverso dagli altri metodi: richiede fino a 5 parametri:

re.sub(pattern, replacement, string, count, flags)

Quindi, se vuoi specificare un flag ma non stai specificando il count, non funzionerà come previsto.

Nessuno fa una riunione in piedi il venerdì, quindi usiamo il submetodo sulla stringa che abbiamo usato per gli esempi search()e findall():

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

res = re.sub(my_regex, "Monday", my_txt, 4, re.IGNORECASE)
print(res) # Output: Every Monday, we have a standup meeting. The only reason why we might not have a meeting on a Monday is public holiday. That Monday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Monday.

Ci sono 4 occorrenze di Fridaynella my_txtstringa. Ecco perché ho specificato 4 come conteggio.

Conclusione

In questo articolo, abbiamo esaminato come importare espressioni regolari tramite il remodulo. Ma non ci siamo fermati qui, poiché ti ho anche illustrato come utilizzare il modulo con i metodi per lavorare con le espressioni regolari in Python.

Inoltre, abbiamo anche dato una breve occhiata a come usare i flag nelle espressioni regolari di Python.

Se trovi utile questo articolo, non esitare a condividerlo con i tuoi amici e familiari.

Fonte: https://www.freecodecamp.org

#python #regex

Come importare un'espressione regolare in Python
许 志强

许 志强

1677766081

如何在 Python 中導入正則表達式

在此 Python RegEx(正則表達式)教程中,您將學習如何在 Python 中導入正則表達式並使用它。將模塊與在 Python 中處理正則表達式的方法一起使用。

幾乎所有的編程語言都支持正則表達式。正則表達式內置於 JavaScript 和 Pearl 等語言中,而其他語言(如 Java 和 Python)具有使用它的標準庫。

在本文中,我們將了解如何在 Python 中導入正則表達式並使用它。我們還將了解 Python 提供的一些處理正則表達式的方法。

目錄:

  • 如何在 Python 中導入正則表達式
  • 如何將 Pythonre模塊與 RegEx 一起使用
    • match()方法的正則表達式示例
    • search()方法的正則表達式示例
    • findall()方法的正則表達式示例
    • split()方法的正則表達式示例
    • sub()方法的正則表達式示例
  • 結論

如何在 Python 中導入正則表達式

Python 提供了re使用正則表達式的模塊。它是 Python 內置的標準模塊,因此如果您擁有最新版本的 Python,則無需使用包管理器單獨安裝它。

re在 Python 中導入模塊,可以使用 import 關鍵字:

import re

如何將 Pythonre模塊與 RegEx 一起使用

Python 提供了一些可用於處理正則表達式的方法,例如match(), search(), findall(),split()sub()

要將這些方法與 RegEx 一起使用,您必須在它們前面加上re模塊和點 ( .),如下所示:

re.match(pattern, string) # to use the match method
re.findall(pattern, string) # to use the findall method 
re.sub(pattern, string) # to use the sub method
re.search(pattern, string) # to use the search method 
re.split(pattern, string) # to use the split method

我提供的 RegEx 示例將使用這些方法。

使用該match()方法的RegEx 示例

接受match()正則表達式和字符串,然後檢查字符串是否與正則表達式中的模式匹配。

這是一個例子:

import re 

my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'

res = re.match(my_regex_1, my_txt)
print(res) # returns None

在上面的例子中:

  • 我有一個my_txt變量設置為freeCodeCamp和一個my_regex_1變量設置為模式^freecodecamp$。這就是您在 Python 中編寫正則表達式的方式——您將它們放在引號內。
  • 為了檢查文本是否與模式匹配,我使用了match()方法並放入了my_regex_1my_txt變量。

字符串是freeCodeCamp,模式是^freecodecamp$,那麼為什麼 match 方法返回了呢None?這是因為找不到匹配項。

變量中有一些大寫字母my_txt,但模式正在尋找小寫字母。

如果您熟悉 JavaScript 或 Pearl 中的 RegEx,則可以使用標誌i來匹配字符串中的所有大寫或小寫字母。

所以,我們需要做的就是使用i標誌來進行匹配。但是在 Python 中使用帶正則表達式的標誌與我們在 JavaScript 中的使用方式不同。

要在 Python 中使用帶有正則表達式的標誌,該re模塊提供IGNORECASEASCIIMULTILINEVERBOSEDOTALLLOCAL選項。

這是在 Python 中使用帶正則表達式的標誌的方式:

re.match(pattern, string, re.ASCII) # to perform only ASCII matching 
re.findall(pattern, string, re.DOTALL) # to match any character – including a new line.
re.sub(pattern, string, re.IGNORECASE) # to perform case insensitive matching
re.search(pattern, string, re.LOCALE) # to perform case insensitive matching dependent on the current locale
re.search(pattern, string, re.VERBOSE) # to allow comments in regex
re.split(pattern, string, re.MULTILINE) # to perform multiple line matching. Commonly used with metacharacters (^ and $)

對於我們的示例,我們可以使用的標誌是IGNORECASE. 讓我們使用它來匹配:

import re 

my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'

res = re.match(my_regex_1, my_txt, re.IGNORECASE)
print(res) #Output: <re.Match object; span=(0, 12), match='freeCodeCamp'>

現在我們有比賽了!

使用該search()方法的RegEx 示例

search()函數接受一個正則表達式和一個字符串,然後返回匹配對像中的第一個匹配項。如果找不到匹配項,則返回None.

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

res = re.search(my_regex, my_txt, re.IGNORECASE)
print(res) # <re.Match object; span=(6, 12), match='Friday'>

您可以看到它返回第一次出現的文本Friday,位於 index6和之間12

您可以使用以下start()方法獲取該索引:

res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located at index ", res.start()) # The first occurrence is located at index  6

您可以像這樣獲取事件的開始和結束索引:

res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located between index", res.start(), "and index", res.end()) # The first occurrence is located between index 6 and index 12

您還可以使用match()withif…else語句:

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

if re.search(my_regex, my_txt, re.IGNORECASE):
    print("Found a match!") #Output: Found a match!
else:
    print("Found no match")   
res = re.search(my_regex, my_txt, re.IGNORECASE)

使用該findall()方法的RegEx 示例

findall()方法接受一個正則表達式和一個字符串,然後查看字符串並找到所有與正則表達式匹配的事件。它將所有這些事件放在一個列表中。

這是一個例子:

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'
res = re.findall(my_regex, my_txt, re.IGNORECASE)

print(res) # Output: ['Friday', 'Friday', 'Friday', 'Friday']

請注意我使用的正則表達式包含文本friday,它不匹配任何出現的“星期五”。該IGNORECASE標誌使它與那些事件相匹配。

使用該split()方法的RegEx 示例

split()方法顧名思義 - 它根據傳遞給它的模式拆分字符串。

如果您想過濾掉字符串中不需要的某些單詞,此方法可能很有用。

import re 

my_txt = "Python and JavaScript and C# and Java and Golang and F#"
my_regex = 'and'

res = re.split(my_regex, my_txt)
print(res) # ['Python ', ' JavaScript ', ' C# ', ' Java ', ' Golang ', ' F#']

使用該sub()方法的RegEx 示例

sub()工作原理類似於 JavaScript 的replace()方法。它替換與傳遞給它的正則表達式相匹配的字符。

sub()方法與其他方法略有不同——它最多需要 5 個參數:

re.sub(pattern, replacement, string, count, flags)

因此,如果您想指定一個標誌但沒有指定count,它將不會按預期工作。

星期五沒有人召開站立會議,所以讓我們在用於和示例sub的字符串上使用該方法:search()findall()

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

res = re.sub(my_regex, "Monday", my_txt, 4, re.IGNORECASE)
print(res) # Output: Every Monday, we have a standup meeting. The only reason why we might not have a meeting on a Monday is public holiday. That Monday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Monday.

Friday字符串中出現 4 次my_txt。這就是為什麼我指定 4 作為計數。

結論

在本文中,我們研究瞭如何通過re模塊導入正則表達式。但我們並沒有就此止步,因為我還向您介紹瞭如何使用該模塊以及在 Python 中處理正則表達式的方法。

此外,我們還簡要了解瞭如何在 Python 正則表達式中使用標誌。

如果您覺得這篇文章有幫助,請不要猶豫,與您的朋友和家人分享。

資料來源: https: //www.freecodecamp.org

#python #regex

如何在 Python 中導入正則表達式