2015-01-27 13 views

Trả lời

9

sử dụng phương pháp danh sách lát

>>> l1 = ['apple', 'pear', 'grapes', 'banana'] 
>>> target_ibdex = l1.index('pear') 
>>> target_ibdex 
1 
>>> l1[:target_ibdex+1] 
['apple', 'pear'] 
>>> 

Với xử lý ngoại lệ khi phần tử không có trong danh sách.

>>> l1 = ['apple', 'pear', 'grapes', 'banana'] 
>>> target_element = "mango" 
>>> try: 
...  target_index = l1.index(target_element) + 1 
... except ValueError, e: 
...  target_index = None 
... 
>>> l1[:target_index] 
['apple', 'pear', 'grapes', 'banana'] 

khi yếu tố có mặt trong danh sách

>>> l1 = ['apple', 'pear', 'grapes', 'banana'] 
>>> target_element = "pear" 
>>> try: 
...  target_index = l1.index(target_element) + 1 
... except ValueError, e: 
...  target_index = None 
... 
>>> l1[:target_index] 
['apple', 'pear'] 
+0

Bạn nên kiểm tra phần tử là một phần của danh sách hoặc thử..catch ValueError –

+0

@HubertGrzeskowiak yes, cập nhật ngay bây giờ. –

+0

Thay vì 'target_index = len (l1)' - bạn chỉ có thể sử dụng 'target_index = None' –

5
l1 = ['apple', 'pear', 'grapes', 'banana'] 
if "pear" in l1: 
    l2 = l1[:l1.index("pear")+1] 
    print l2 

Output:

[ 'táo', 'lê']

5

Bạn có thể xây dựng một chức năng máy phát điện tùy chỉnh mà sẽ làm việc trên bất kỳ iterable, không chỉ liệt kê - mặc dù ví dụ của bạn, list.index, xử lý ngoại lệ và cắt là tốt ...

def takewhile_including(iterable, value): 
    for it in iterable: 
     yield it 
     if it == value: 
      return 

l1 = ['apple', 'pear', 'grapes', 'banana'] 
print('Until pear', list(takewhile_including(l1, 'pear'))) 
# Until pear ['apple', 'pear'] 
print('Until blah', list(takewhile_including(l1, 'blah'))) 
# Until blah ['apple', 'pear', 'grapes', 'banana'] 
0
l1 = ['apple', 'pear', 'grapes', 'banana'] 
l1 = [x for x in l1[0:l1.index(<target>)+1]] 

Suy diễn nó ra một chức năng, cho mô đun và tái sử dụng sẽ là lý tưởng.

>>> li 
['apple', 'orange', 'pear', 'tomato'] 
>>> 
>>> def slice_and_dice(fruit, fruits): 
...  
     if fruit in fruits: 
...  slice = [fr for fr in l1[:fruits.index(fruit)+1]] 
...  return slice 
... 
>>> slice_and_dice('pear', li) 
['apple', 'orange', 'pear'] 
+1

[fr cho fr trong l1 [: fruits.index (fruit) +1]] có thể viết ngắn hơn là l1 [: fruits.index (fruit) +1]. Danh sách hiểu ở đây không có lợi ích. –

+0

Nó cũng có thể ngắn hơn nếu tôi bao gồm các điều kiện bên trong nó, lợi ích tôi có để hiểu danh sách dễ đọc hơn, không giống nhau cho tất cả mọi người. – AutonomouSystem

+0

mã phụ không cần thiết dễ đọc như thế nào? –

2

Vâng, tôi đã quan tâm tốc độ của từng giải pháp. Đây là đoạn mã và ước tính:

setup = """ 
from itertools import takewhile, dropwhile 

def dropwhile_v1(iterable, sentinel): 
    return reversed(list(dropwhile(lambda x: x != sentinel, reversed(iterable)))) 

def dropwhile_v2(iterable, sentinel): 
    return list(dropwhile(lambda x: x != sentinel, iterable[::-1]))[::-1] 


def dropwhile_jon(iterable, sentinel): 
    for item in iterable: 
     yield item 
     if item == sentinel: 
      return 

def dropwhile_vivek(iterable, sentinel): 
    try: 
     target_index = iterable.index(sentinel) + 1 
    except ValueError: 
     target_index = None 

    return iterable[:target_index] 

def dropwhile_autonomou(iterable, sentinel): 
    if sentinel in iterable: 
     slice = [fr for fr in iterable[:fruits.index(sentinel)+1]] 
     return slice 


from random import uniform 
seq = [uniform(1,100) for _ in range(100)] 

def test(callable): 
    sentinel = uniform(1,100) 
    callable(seq, sentinel) 
""" 

import timeit 
for method in ['dropwhile_v1', 'dropwhile_v2', 'dropwhile_vivek', 'dropwhile_jon', 'dropwhile_autonomou']: 
    print ('%s: %fs' % (method, timeit.timeit('test(%s)' % method, setup=setup, number=1000000))) 

Output:

dropwhile_v1: 12.979626s 
dropwhile_v2: 13.234087s 
dropwhile_vivek: 3.883617s 
dropwhile_jon: 0.622481s 
dropwhile_autonomou: 2.100633s 
+3

Để kiểm tra chính xác 'dropwhile_jon' - bạn cần phải thực hiện danh sách để so sánh táo với táo - ngược lại, thử nghiệm chỉ là khởi tạo chức năng máy phát điện –

+0

Ngoài ra bạn có "trái cây" trong đó, nơi nó nên được "lặp lại" tôi nghĩ. –

+1

Khác với bạn nên kiểm tra với cùng một sentinel cho tất cả các phương pháp, không phải với những người ngẫu nhiên. –

Các vấn đề liên quan