Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Python 2.6+ và Python 3:

Nếu bạn muốn

a = []
item = next(x for x in a)
2 được nâng lên nếu không tìm thấy phần tử phù hợp nào:

next(x for x in the_iterable if x > 3)

Nếu bạn muốn

a = []
item = next(x for x in a)
3 (ví dụ:
a = []
item = next(x for x in a)
4) được trả về thay thế:

next((x for x in the_iterable if x > 3), default_value)

Lưu ý rằng bạn cần thêm một cặp dấu ngoặc đơn xung quanh biểu thức máy phát trong trường hợp này - chúng cần thiết bất cứ khi nào biểu thức trình tạo không phải là đối số duy nhất.

Tôi thấy hầu hết các câu trả lời kiên quyết bỏ qua

a = []
item = next(x for x in a)
5 tích hợp và vì vậy tôi cho rằng vì một lý do bí ẩn nào đó, chúng tập trung 100% vào các phiên bản 2.5 trở lên-mà không đề cập đến vấn đề phiên bản Python (nhưng sau đó tôi không thấy đề cập đến Trong các câu trả lời đề cập đến
a = []
item = next(x for x in a)
5 tích hợp, đó là lý do tại sao tôi nghĩ rằng cần phải tự cung cấp câu trả lời-ít nhất là vấn đề "phiên bản chính xác" được ghi lại theo cách này ;-).

Python

Phương pháp

a = []
item = next(x for x in a)
7 của các trình lặp ngay lập tức tăng
a = []
item = next(x for x in a)
2 nếu trình lặp ngay lập tức kết thúc - tức là, đối với trường hợp sử dụng của bạn, nếu không có mục nào trong điều kiện thỏa mãn điều kiện. Nếu bạn không quan tâm (tức là, bạn biết phải có ít nhất một mục thỏa đáng) thì chỉ cần sử dụng ____37 (tốt nhất trên GenExp, dòng cho
a = []
item = next(x for x in a)
5 tích hợp trong Python 2.6 và tốt hơn).must be at least one satisfactory item) then just use
a = []
item = next(x for x in a)
7 (best on a genexp, line for the
a = []
item = next(x for x in a)
5 built-in in Python 2.6 and better).

Nếu bạn quan tâm, hãy gói mọi thứ trong một chức năng như bạn đã chỉ ra lần đầu tiên trong Q của bạn có vẻ tốt nhất và trong khi việc thực hiện chức năng mà bạn đề xuất chỉ tốt, bạn có thể sử dụng thay thế

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
1, vòng lặp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
2 hoặc GenExp hoặc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
3 như Cơ thể của chức năng, như các câu trả lời khác nhau đã đề xuất. Không có nhiều giá trị gia tăng trong bất kỳ lựa chọn thay thế nào vì vậy tôi sẽ sử dụng phiên bản đơn giản hoàn toàn mà bạn đã đề xuất lần đầu tiên.

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Tế bào thần kinh

4.5844 Huy hiệu vàng32 Huy hiệu bạc53 Huy hiệu Đồng4 gold badges32 silver badges53 bronze badges

Đã trả lời ngày 2 tháng 3 năm 2010 lúc 15:29Mar 2, 2010 at 15:29

Alex Martellialex MartelliAlex Martelli

825K163 Huy hiệu vàng1203 Huy hiệu bạc1380 Huy hiệu Đồng163 gold badges1203 silver badges1380 bronze badges

8

Ngoại lệ chết tiệt!

Tôi thích câu trả lời này. Tuy nhiên, kể từ khi

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
4 tăng ngoại lệ
a = []
item = next(x for x in a)
2 khi không có vật phẩm, tôi sẽ sử dụng đoạn trích sau để tránh ngoại lệ:

a = []
item = next((x for x in a), None)

Ví dụ,

a = []
item = next(x for x in a)

Sẽ tăng ngoại lệ

a = []
item = next(x for x in a)
2;

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Đã trả lời ngày 20 tháng 1 năm 2016 lúc 7:49Jan 20, 2016 at 7:49

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

0

Như một chức năng có thể sử dụng lại, được ghi lại và thử nghiệm

def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))

Phiên bản với đối số mặc định

@Zorf đã đề xuất một phiên bản của chức năng này, nơi bạn có thể có giá trị trả về được xác định trước nếu có thể trống hoặc không có mục nào phù hợp với điều kiện:

def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise

Đã trả lời ngày 19 tháng 2 năm 2016 lúc 19:25Feb 19, 2016 at 19:25

10

Cách hiệu quả nhất trong Python 3 là một trong những điều sau đây (sử dụng một ví dụ tương tự):

Với phong cách "hiểu":

next(i for i in range(100000000) if i == 1000)

CẢNH BÁO: Biểu thức cũng hoạt động với Python 2, nhưng trong ví dụ được sử dụng

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
7 trả về một đối tượng có thể lặp lại trong Python 3 thay vì một danh sách như Python 2 (nếu bạn muốn xây dựng một sự khác biệt trong Python 2 sử dụng
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
8).
: The expression works also with Python 2, but in the example is used
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
7 that returns an iterable object in Python 3 instead of a list like Python 2 (if you want to construct an iterable in Python 2 use
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
8 instead).

Lưu ý rằng biểu thức tránh để xây dựng một danh sách trong biểu thức hiểu

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
9, điều đó sẽ gây ra một danh sách với tất cả các phần tử trước khi lọc các phần tử và sẽ gây ra xử lý toàn bộ các tùy chọn, thay vì dừng lần lặp một lần
def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))
0.

Với phong cách "chức năng":

________số 8

Cảnh báo: Điều này không hoạt động trong Python 2, thậm chí thay thế

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
7 bằng
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
8 do
def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))
3 tạo danh sách thay vì trình lặp (không hiệu quả) và hàm
a = []
item = next(x for x in a)
5 chỉ hoạt động với trình lặp.
: This doesn't work in Python 2, even replacing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
7 with
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
8 due that
def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))
3 create a list instead of a iterator (inefficient), and the
a = []
item = next(x for x in a)
5 function only works with iterators.

Giá trị mặc định

Như đã đề cập trong các phản hồi khác, bạn phải thêm một tham số ngoài chức năng

a = []
item = next(x for x in a)
5 nếu bạn muốn tránh một ngoại lệ được nêu ra khi điều kiện không được đáp ứng.

Phong cách "chức năng":

next(filter(lambda i: i == 1000, range(100000000)), False)

Phong cách "Hiểu":

Với phong cách này, bạn cần bao quanh biểu thức hiểu với

def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))
6 để tránh
def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))
7:

next((x for x in the_iterable if x > 3), default_value)
0

Đã trả lời ngày 8 tháng 1 năm 2018 lúc 17:30Jan 8, 2018 at 17:30

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Mariano Ruizmariano RuizMariano Ruiz

4.0162 Huy hiệu vàng36 Huy hiệu bạc34 Huy hiệu đồng2 gold badges36 silver badges34 bronze badges

1

Tương tự như sử dụng

def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))
8, bạn có thể sử dụng biểu thức máy phát:

next((x for x in the_iterable if x > 3), default_value)
1

Trong cả hai trường hợp, bạn có thể muốn bắt

a = []
item = next(x for x in a)
2 mặc dù, trong trường hợp không có yếu tố nào thỏa mãn tình trạng của bạn.

Về mặt kỹ thuật, tôi cho rằng bạn có thể làm điều gì đó như thế này:

next((x for x in the_iterable if x > 3), default_value)
2

Nó sẽ tránh phải tạo một khối

def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise
0. Nhưng điều đó có vẻ khó hiểu và lạm dụng cú pháp.

Đã trả lời ngày 2 tháng 3 năm 2010 lúc 7:27Mar 2, 2010 at 7:27

Matt Andersonmatt AndersonMatt Anderson

18.7K11 Huy hiệu vàng39 Huy hiệu bạc55 Huy hiệu Đồng11 gold badges39 silver badges55 bronze badges

2

Tôi sẽ viết cái này

next((x for x in the_iterable if x > 3), default_value)
3

Đã trả lời ngày 2 tháng 3 năm 2010 lúc 8:22Mar 2, 2010 at 8:22

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Mike Grahammike GrahamMike Graham

71K14 Huy hiệu vàng97 Huy hiệu bạc129 Huy hiệu đồng14 gold badges97 silver badges129 bronze badges

1

Đối với bất kỳ ai sử dụng Python 3.8 hoặc mới hơn, tôi khuyên bạn nên sử dụng "Biểu thức gán" như được mô tả trong PEP 572 - Biểu thức gán.

next((x for x in the_iterable if x > 3), default_value)
4

Đã trả lời ngày 26 tháng 2 năm 2021 lúc 20:03Feb 26, 2021 at 20:03

không khíairborne

3.2143 huy hiệu vàng14 Huy hiệu bạc24 Huy hiệu đồng3 gold badges14 silver badges24 bronze badges

5

Mô -đun

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
1 chứa hàm bộ lọc cho các trình lặp. Phần tử đầu tiên của trình lặp được lọc có thể thu được bằng cách gọi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
4 trên đó:

next((x for x in the_iterable if x > 3), default_value)
5

Đã trả lời ngày 2 tháng 3 năm 2010 lúc 7:16Mar 2, 2010 at 7:16

STHSTHsth

Phim thương hiệu vàng 215k5050 gold badges273 silver badges363 bronze badges

3

Đối với các phiên bản Python cũ hơn, nơi tích hợp tiếp theo không tồn tại:

next((x for x in the_iterable if x > 3), default_value)
6

Đã trả lời ngày 2 tháng 3 năm 2010 lúc 9:02Mar 2, 2010 at 9:02

Menno Smitsmenno SmitsMenno Smits

1.8741 Huy hiệu vàng12 Huy hiệu bạc12 Huy hiệu đồng1 gold badge12 silver badges12 bronze badges

0

Bằng cách sử dụng

next((x for x in the_iterable if x > 3), default_value)
7

Người ta có thể kiểm tra điều kiện của giá trị của mục đầu tiên trong_iterable và có được chỉ mục của nó mà không cần phải đánh giá tất cả các mục trong_iterable.

Biểu thức hoàn chỉnh để sử dụng là

next((x for x in the_iterable if x > 3), default_value)
8

Ở đây First_index giả định giá trị của giá trị đầu tiên được xác định trong biểu thức được thảo luận ở trên.first_index assumes the value of the first value identified in the expression discussed above.

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Bill Bell

20.4K5 Huy hiệu vàng42 Huy hiệu bạc57 Huy hiệu đồng5 gold badges42 silver badges57 bronze badges

Đã trả lời ngày 21 tháng 11 năm 2016 lúc 14:24Nov 21, 2016 at 14:24

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

blue_noteblue_noteblue_note

26K7 Huy hiệu vàng61 Huy hiệu bạc83 Huy hiệu Đồng7 gold badges61 silver badges83 bronze badges

0

Câu hỏi này đã có câu trả lời tuyệt vời. Tôi chỉ thêm hai xu của mình vì tôi đã hạ cánh ở đây để cố gắng tìm giải pháp cho vấn đề của riêng tôi, rất giống với OP.

Nếu bạn muốn tìm chỉ mục của mục đầu tiên khớp với tiêu chí bằng cách sử dụng trình tạo, bạn có thể chỉ cần làm:

next((x for x in the_iterable if x > 3), default_value)
9

Đã trả lời ngày 10 tháng 5 năm 2017 lúc 15:25May 10, 2017 at 15:25

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Dangomdangomdangom

10,4K9 Huy hiệu vàng41 Huy hiệu bạc68 Huy hiệu Đồng9 gold badges41 silver badges68 bronze badges

1

Trong Python 3:

a = []
item = next((x for x in a), None)
0

Trong Python 2.6:

a = []
item = next((x for x in a), None)
1

EDIT: Tôi nghĩ rằng nó là hiển nhiên, nhưng rõ ràng không phải: thay vì

a = []
item = next(x for x in a)
4, bạn có thể vượt qua một hàm (hoặc
def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise
4) với kiểm tra điều kiện:

a = []
item = next((x for x in a), None)
2

Đã trả lời ngày 29 tháng 4 năm 2016 lúc 15:14Apr 29, 2016 at 15:14

Berislav Lopacberislav LopacBerislav Lopac

15.8k6 huy hiệu vàng68 Huy hiệu bạc78 Huy hiệu đồng6 gold badges68 silver badges78 bronze badges

Bạn cũng có thể sử dụng chức năng

def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise
5 trong Numpy. Ví dụ:

i) Tìm "L" đầu tiên trong "Helloworld":

a = []
item = next((x for x in a), None)
3

ii) Tìm số ngẫu nhiên đầu tiên> 0,1

a = []
item = next((x for x in a), None)
4

iii) Tìm số ngẫu nhiên cuối cùng> 0,1

a = []
item = next((x for x in a), None)
5

Đã trả lời ngày 24 tháng 1 năm 2019 lúc 21:58Jan 24, 2019 at 21:58

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Aimaimaim

6372 Huy hiệu vàng11 Huy hiệu bạc25 Huy hiệu Đồng2 gold badges11 silver badges25 bronze badges

Đây là một tốc độ nhất trong ba cách. Tiếp theo () không phải là cách nhanh nhất.

a = []
item = next((x for x in a), None)
6

Kết quả để:

a = []
item = next((x for x in a), None)
7

Đã trả lời ngày 1 tháng 12 năm 2021 lúc 15:55Dec 1, 2021 at 15:55

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

LukaslukasLukas

4013 Huy hiệu bạc11 Huy hiệu đồng3 silver badges11 bronze badges

Tôi biết nó đã quá muộn nhưng vẫn vậy, đây là câu trả lời của tôi:

a = []
item = next((x for x in a), None)
8

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

Đã trả lời ngày 17 tháng 9 lúc 12:46Sep 17 at 12:46

Hướng dẫn python get first element of list that matches condition - python lấy phần tử đầu tiên của danh sách phù hợp với điều kiện

1

Nếu bạn không muốn sử dụng

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
4, bạn có thể sử dụng giải nén:

a = []
item = next((x for x in a), None)
9

Lưu ý rằng sử dụng

def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise
7 tương đương với việc viết
def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise
8 Docs Python.

Nếu bạn cần hỗ trợ cho trường hợp cạnh, bạn có thể viết như thế này:

a = []
item = next(x for x in a)
0

Đã trả lời ngày 28 tháng 9 lúc 8:38Sep 28 at 8:38

JakethesnakejakethesnakeJakeTheSnake

2.4263 Huy hiệu vàng13 Huy hiệu bạc25 Huy hiệu Đồng3 gold badges13 silver badges25 bronze badges

Oneliner:

a = []
item = next(x for x in a)
1

Nếu bạn không chắc chắn rằng bất kỳ yếu tố nào sẽ hợp lệ theo các tiêu chí, bạn nên gửi kèm theo điều này với

def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise
0 vì
next(i for i in range(100000000) if i == 1000)
0 có thể tăng
next(i for i in range(100000000) if i == 1000)
1.

Đã trả lời ngày 2 tháng 3 năm 2010 lúc 8:34Mar 2, 2010 at 8:34

MizipzormizipzorMizipzor

49.6K22 Huy hiệu vàng94 Huy hiệu bạc138 Huy hiệu đồng22 gold badges94 silver badges138 bronze badges

3

Làm thế nào để bạn tìm thấy chỉ số của các yếu tố danh sách đáp ứng một điều kiện trong Python?

Sử dụng danh sách hiểu. Sử dụng Enumerate () để tạo danh sách các bộ dữ liệu (chỉ mục, giá trị) từ danh sách đầu vào a_list. Sử dụng danh sách hiểu biết trong danh sách các bộ dữ liệu này để chọn mọi chỉ mục tương ứng với một giá trị đáp ứng điều kiện đã cho và trả về các lựa chọn làm danh sách.. Use enumerate() to create a list of (index, value) tuples from the input list a_list . Use a list comprehension on this list of tuples to select every index that corresponds to a value that meets the given condition, and return the selections as a list.

Làm thế nào để bạn tham khảo phần tử đầu tiên trong danh sách Python?

Để truy cập phần tử đầu tiên (12) của danh sách, chúng ta có thể sử dụng cú pháp đăng ký [] bằng cách chuyển chỉ mục 0.Trong danh sách Python không được chỉ số bằng không, do đó, phần tử đầu tiên có sẵn tại Index 0.Tương tự, chúng ta cũng có thể sử dụng cú pháp cắt [: 1] để có được phần tử đầu tiên của danh sách trong Python.use the subscript syntax [ ] by passing an index 0 . In Python lists are zero-indexed, so the first element is available at index 0 . Similarly, we can also use the slicing syntax [:1] to get the first element of a list in Python.

Làm thế nào để bạn trích xuất phần tử đầu tiên của một danh sách?

Để chỉ trích xuất phần tử đầu tiên từ một danh sách, chúng ta có thể sử dụng hàm SAPPLY và truy cập phần tử đầu tiên bằng dấu ngoặc vuông.Ví dụ: nếu chúng ta có một danh sách gọi là Danh sách chứa 5 phần tử, mỗi phần tử chứa 20 phần tử thì phần tử phụ đầu tiên có thể được trích xuất bằng cách sử dụng lệnh saply (danh sách, "[", 1).use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).

Làm thế nào để bạn tìm thấy chỉ mục của một giá trị trong danh sách Python?

Phương thức Index () trả về chỉ mục của phần tử được chỉ định trong danh sách ...
Phần tử - Phần tử sẽ được tìm kiếm ..
Bắt đầu (Tùy chọn) - Bắt đầu tìm kiếm từ chỉ mục này ..
End (Tùy chọn) - Tìm kiếm phần tử lên đến chỉ mục này ..