Hướng dẫn find index of all occurrences of a character in a list python - tìm chỉ mục của tất cả các lần xuất hiện của một ký tự trong danh sách python

Tạo một máy phát điện

Máy phát điện nhanh và sử dụng dấu chân bộ nhớ nhỏ. Họ cung cấp cho bạn sự linh hoạt trong cách bạn sử dụng kết quả.

def indices(iter, val):
    """Generator: Returns all indices of val in iter
    Raises a ValueError if no val does not occur in iter
    Passes on the AttributeError if iter does not have an index method (e.g. is a set)
    """
    i = -1
    NotFound = False
    while not NotFound:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            NotFound = True
        else:
            yield i
    if i == -1:
        raise ValueError("No occurrences of {v} in {i}".format(v = val, i = iter))

Mã trên có thể được sử dụng để tạo danh sách các chỉ số: list(indices(input,value)); Sử dụng chúng làm khóa từ điển: dict(indices(input,value)); Tổng hợp chúng: sum(indices(input,value)); trong A cho vòng for index_ in indices(input,value):; ... vv ... mà không tạo ra một danh sách tạm thời/tuple hoặc tương tự.

Trong một vòng lặp For, bạn sẽ lấy lại chỉ mục tiếp theo của mình khi bạn gọi cho nó mà không cần chờ tất cả các khác được tính toán trước. Điều đó có nghĩa là: nếu bạn thoát ra khỏi vòng lặp vì một số lý do bạn tiết kiệm thời gian cần thiết để tìm các chỉ số bạn không bao giờ cần.

Làm thế nào nó hoạt động

  • Gọi .index trên đầu vào iter để tìm sự xuất hiện tiếp theo của val
  • Sử dụng tham số thứ hai cho .index để bắt đầu tại điểm sau lần xuất hiện cuối cùng
  • Mang lại chỉ số
  • Lặp lại cho đến khi
    @version("WhileTrueBreak", versions)
    def indices2(iter, val):
        i = -1
        while True:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                break
            else:
                yield i
    
    @version("WhileErrFalse", versions)
    def indices5(iter, val):
        i = -1
        err = False
        while not err:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                err = True
            else:
                yield i
    
    @version("RemainingSlice", versions)
    def indices1(iter, val):
        i = 0
        while val in iter[i:]:
            i = iter.index(val, i)
            yield i
            i += 1
    
    @version("LastOccurrence", versions)
    def indices4(iter,val):
        i = 0
        last = len(iter) - tuple(reversed(iter)).index(val)
        while i < last:
            i = iter.index(val, i)
            yield i
            i += 1
    
    1 tăng
    @version("WhileTrueBreak", versions)
    def indices2(iter, val):
        i = -1
        while True:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                break
            else:
                yield i
    
    @version("WhileErrFalse", versions)
    def indices5(iter, val):
        i = -1
        err = False
        while not err:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                err = True
            else:
                yield i
    
    @version("RemainingSlice", versions)
    def indices1(iter, val):
        i = 0
        while val in iter[i:]:
            i = iter.index(val, i)
            yield i
            i += 1
    
    @version("LastOccurrence", versions)
    def indices4(iter,val):
        i = 0
        last = len(iter) - tuple(reversed(iter)).index(val)
        while i < last:
            i = iter.index(val, i)
            yield i
            i += 1
    
    2

Phiên bản thay thế

Tôi đã thử bốn phiên bản khác nhau để điều khiển dòng chảy; Hai EAFP (sử dụng

@version("WhileTrueBreak", versions)
def indices2(iter, val):
    i = -1
    while True:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            break
        else:
            yield i

@version("WhileErrFalse", versions)
def indices5(iter, val):
    i = -1
    err = False
    while not err:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            err = True
        else:
            yield i

@version("RemainingSlice", versions)
def indices1(iter, val):
    i = 0
    while val in iter[i:]:
        i = iter.index(val, i)
        yield i
        i += 1

@version("LastOccurrence", versions)
def indices4(iter,val):
    i = 0
    last = len(iter) - tuple(reversed(iter)).index(val)
    while i < last:
        i = iter.index(val, i)
        yield i
        i += 1
3) và hai TBYL (có thử nghiệm hợp lý trong câu lệnh
@version("WhileTrueBreak", versions)
def indices2(iter, val):
    i = -1
    while True:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            break
        else:
            yield i

@version("WhileErrFalse", versions)
def indices5(iter, val):
    i = -1
    err = False
    while not err:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            err = True
        else:
            yield i

@version("RemainingSlice", versions)
def indices1(iter, val):
    i = 0
    while val in iter[i:]:
        i = iter.index(val, i)
        yield i
        i += 1

@version("LastOccurrence", versions)
def indices4(iter,val):
    i = 0
    last = len(iter) - tuple(reversed(iter)).index(val)
    while i < last:
        i = iter.index(val, i)
        yield i
        i += 1
4):

  1. "Whiletruebreak":
    @version("WhileTrueBreak", versions)
    def indices2(iter, val):
        i = -1
        while True:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                break
            else:
                yield i
    
    @version("WhileErrFalse", versions)
    def indices5(iter, val):
        i = -1
        err = False
        while not err:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                err = True
            else:
                yield i
    
    @version("RemainingSlice", versions)
    def indices1(iter, val):
        i = 0
        while val in iter[i:]:
            i = iter.index(val, i)
            yield i
            i += 1
    
    @version("LastOccurrence", versions)
    def indices4(iter,val):
        i = 0
        last = len(iter) - tuple(reversed(iter)).index(val)
        while i < last:
            i = iter.index(val, i)
            yield i
            i += 1
    
    5 ...
    @version("WhileTrueBreak", versions)
    def indices2(iter, val):
        i = -1
        while True:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                break
            else:
                yield i
    
    @version("WhileErrFalse", versions)
    def indices5(iter, val):
        i = -1
        err = False
        while not err:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                err = True
            else:
                yield i
    
    @version("RemainingSlice", versions)
    def indices1(iter, val):
        i = 0
        while val in iter[i:]:
            i = iter.index(val, i)
            yield i
            i += 1
    
    @version("LastOccurrence", versions)
    def indices4(iter,val):
        i = 0
        last = len(iter) - tuple(reversed(iter)).index(val)
        while i < last:
            i = iter.index(val, i)
            yield i
            i += 1
    
    6. Đáng ngạc nhiên, đây thường là một cú chạm chậm hơn tùy chọn 2 và (IMV) không thể đọc được
  2. "WHREERRFALSE": Sử dụng biến bool
    @version("WhileTrueBreak", versions)
    def indices2(iter, val):
        i = -1
        while True:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                break
            else:
                yield i
    
    @version("WhileErrFalse", versions)
    def indices5(iter, val):
        i = -1
        err = False
        while not err:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                err = True
            else:
                yield i
    
    @version("RemainingSlice", versions)
    def indices1(iter, val):
        i = 0
        while val in iter[i:]:
            i = iter.index(val, i)
            yield i
            i += 1
    
    @version("LastOccurrence", versions)
    def indices4(iter,val):
        i = 0
        last = len(iter) - tuple(reversed(iter)).index(val)
        while i < last:
            i = iter.index(val, i)
            yield i
            i += 1
    
    7 để xác định khi nào
    @version("WhileTrueBreak", versions)
    def indices2(iter, val):
        i = -1
        while True:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                break
            else:
                yield i
    
    @version("WhileErrFalse", versions)
    def indices5(iter, val):
        i = -1
        err = False
        while not err:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                err = True
            else:
                yield i
    
    @version("RemainingSlice", versions)
    def indices1(iter, val):
        i = 0
        while val in iter[i:]:
            i = iter.index(val, i)
            yield i
            i += 1
    
    @version("LastOccurrence", versions)
    def indices4(iter,val):
        i = 0
        last = len(iter) - tuple(reversed(iter)).index(val)
        while i < last:
            i = iter.index(val, i)
            yield i
            i += 1
    
    2 được nâng lên. Đây thường là nhanh nhất và dễ đọc hơn 1
  3. "ReselingSlice": Kiểm tra xem Val có ở phần còn lại của đầu vào bằng cách sử dụng cắt không:
    @version("WhileTrueBreak", versions)
    def indices2(iter, val):
        i = -1
        while True:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                break
            else:
                yield i
    
    @version("WhileErrFalse", versions)
    def indices5(iter, val):
        i = -1
        err = False
        while not err:
            try:
                i = iter.index(val, i+1)
            except ValueError:
                err = True
            else:
                yield i
    
    @version("RemainingSlice", versions)
    def indices1(iter, val):
        i = 0
        while val in iter[i:]:
            i = iter.index(val, i)
            yield i
            i += 1
    
    @version("LastOccurrence", versions)
    def indices4(iter,val):
        i = 0
        last = len(iter) - tuple(reversed(iter)).index(val)
        while i < last:
            i = iter.index(val, i)
            yield i
            i += 1
    
    9 hay không. Không có gì đáng ngạc nhiên, điều này không mở rộng quy mô
  4. "Lastoccurrence": Kiểm tra trước khi xảy ra lần cuối cùng, hãy tiếp tục đi
    Length: 100, Ocurrences: 4.0%
    {'WhileTrueBreak': 0.0074799987487494946, 'WhileErrFalse': 0.006440002471208572, 'RemainingSlice': 0.01221001148223877, 'LastOccurrence': 0.00801000278443098}
    Length: 1000, Ocurrences: 1.2%
    {'WhileTrueBreak': 0.03101000329479575, 'WhileErrFalse': 0.0278000021353364, 'RemainingSlice': 0.08278000168502331, 'LastOccurrence': 0.03986000083386898}
    Length: 10000, Ocurrences: 2.05%
    {'WhileTrueBreak': 0.18062000162899494, 'WhileErrFalse': 0.1810499932616949, 'RemainingSlice': 2.9145700042136014, 'LastOccurrence': 0.2049500006251037}
    Length: 100000, Ocurrences: 1.977%
    {'WhileTrueBreak': 1.9361200043931603, 'WhileErrFalse': 1.7280600033700466, 'RemainingSlice': 254.4725100044161, 'LastOccurrence': 1.9101499929092824}
    Length: 100000, Ocurrences: 9.873%
    {'WhileTrueBreak': 2.832529996521771, 'WhileErrFalse': 2.9984100023284554, 'RemainingSlice': 1132.4922299943864, 'LastOccurrence': 2.6660699979402125}
    Length: 100000, Ocurrences: 25.058%
    {'WhileTrueBreak': 5.119729996658862, 'WhileErrFalse': 5.2082200068980455, 'RemainingSlice': 2443.0577100021765, 'LastOccurrence': 4.75954000139609}
    Length: 100000, Ocurrences: 49.698%
    {'WhileTrueBreak': 9.372120001353323, 'WhileErrFalse': 8.447749994229525, 'RemainingSlice': 5042.717969999649, 'LastOccurrence': 8.050809998530895}
    
    0

Sự khác biệt về hiệu suất tổng thể giữa 1,2 và 4 là không đáng kể, do đó, nó thuộc về phong cách và sở thích cá nhân. Cho rằng .index sử dụng

@version("WhileTrueBreak", versions)
def indices2(iter, val):
    i = -1
    while True:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            break
        else:
            yield i

@version("WhileErrFalse", versions)
def indices5(iter, val):
    i = -1
    err = False
    while not err:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            err = True
        else:
            yield i

@version("RemainingSlice", versions)
def indices1(iter, val):
    i = 0
    while val in iter[i:]:
        i = iter.index(val, i)
        yield i
        i += 1

@version("LastOccurrence", versions)
def indices4(iter,val):
    i = 0
    last = len(iter) - tuple(reversed(iter)).index(val)
    while i < last:
        i = iter.index(val, i)
        yield i
        i += 1
2 để cho bạn biết nó không tìm thấy gì, thay vì ví dụ: Trở về
Length: 100, Ocurrences: 4.0%
{'WhileTrueBreak': 0.0074799987487494946, 'WhileErrFalse': 0.006440002471208572, 'RemainingSlice': 0.01221001148223877, 'LastOccurrence': 0.00801000278443098}
Length: 1000, Ocurrences: 1.2%
{'WhileTrueBreak': 0.03101000329479575, 'WhileErrFalse': 0.0278000021353364, 'RemainingSlice': 0.08278000168502331, 'LastOccurrence': 0.03986000083386898}
Length: 10000, Ocurrences: 2.05%
{'WhileTrueBreak': 0.18062000162899494, 'WhileErrFalse': 0.1810499932616949, 'RemainingSlice': 2.9145700042136014, 'LastOccurrence': 0.2049500006251037}
Length: 100000, Ocurrences: 1.977%
{'WhileTrueBreak': 1.9361200043931603, 'WhileErrFalse': 1.7280600033700466, 'RemainingSlice': 254.4725100044161, 'LastOccurrence': 1.9101499929092824}
Length: 100000, Ocurrences: 9.873%
{'WhileTrueBreak': 2.832529996521771, 'WhileErrFalse': 2.9984100023284554, 'RemainingSlice': 1132.4922299943864, 'LastOccurrence': 2.6660699979402125}
Length: 100000, Ocurrences: 25.058%
{'WhileTrueBreak': 5.119729996658862, 'WhileErrFalse': 5.2082200068980455, 'RemainingSlice': 2443.0577100021765, 'LastOccurrence': 4.75954000139609}
Length: 100000, Ocurrences: 49.698%
{'WhileTrueBreak': 9.372120001353323, 'WhileErrFalse': 8.447749994229525, 'RemainingSlice': 5042.717969999649, 'LastOccurrence': 8.050809998530895}
3, một người tiếp cận EAFP có vẻ phù hợp với tôi.

Dưới đây là 4 biến thể mã và kết quả từ

Length: 100, Ocurrences: 4.0%
{'WhileTrueBreak': 0.0074799987487494946, 'WhileErrFalse': 0.006440002471208572, 'RemainingSlice': 0.01221001148223877, 'LastOccurrence': 0.00801000278443098}
Length: 1000, Ocurrences: 1.2%
{'WhileTrueBreak': 0.03101000329479575, 'WhileErrFalse': 0.0278000021353364, 'RemainingSlice': 0.08278000168502331, 'LastOccurrence': 0.03986000083386898}
Length: 10000, Ocurrences: 2.05%
{'WhileTrueBreak': 0.18062000162899494, 'WhileErrFalse': 0.1810499932616949, 'RemainingSlice': 2.9145700042136014, 'LastOccurrence': 0.2049500006251037}
Length: 100000, Ocurrences: 1.977%
{'WhileTrueBreak': 1.9361200043931603, 'WhileErrFalse': 1.7280600033700466, 'RemainingSlice': 254.4725100044161, 'LastOccurrence': 1.9101499929092824}
Length: 100000, Ocurrences: 9.873%
{'WhileTrueBreak': 2.832529996521771, 'WhileErrFalse': 2.9984100023284554, 'RemainingSlice': 1132.4922299943864, 'LastOccurrence': 2.6660699979402125}
Length: 100000, Ocurrences: 25.058%
{'WhileTrueBreak': 5.119729996658862, 'WhileErrFalse': 5.2082200068980455, 'RemainingSlice': 2443.0577100021765, 'LastOccurrence': 4.75954000139609}
Length: 100000, Ocurrences: 49.698%
{'WhileTrueBreak': 9.372120001353323, 'WhileErrFalse': 8.447749994229525, 'RemainingSlice': 5042.717969999649, 'LastOccurrence': 8.050809998530895}
4 (tính bằng mili giây) cho các độ dài khác nhau của đầu vào và độ thưa của các trận đấu

@version("WhileTrueBreak", versions)
def indices2(iter, val):
    i = -1
    while True:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            break
        else:
            yield i

@version("WhileErrFalse", versions)
def indices5(iter, val):
    i = -1
    err = False
    while not err:
        try:
            i = iter.index(val, i+1)
        except ValueError:
            err = True
        else:
            yield i

@version("RemainingSlice", versions)
def indices1(iter, val):
    i = 0
    while val in iter[i:]:
        i = iter.index(val, i)
        yield i
        i += 1

@version("LastOccurrence", versions)
def indices4(iter,val):
    i = 0
    last = len(iter) - tuple(reversed(iter)).index(val)
    while i < last:
        i = iter.index(val, i)
        yield i
        i += 1
Length: 100, Ocurrences: 4.0%
{'WhileTrueBreak': 0.0074799987487494946, 'WhileErrFalse': 0.006440002471208572, 'RemainingSlice': 0.01221001148223877, 'LastOccurrence': 0.00801000278443098}
Length: 1000, Ocurrences: 1.2%
{'WhileTrueBreak': 0.03101000329479575, 'WhileErrFalse': 0.0278000021353364, 'RemainingSlice': 0.08278000168502331, 'LastOccurrence': 0.03986000083386898}
Length: 10000, Ocurrences: 2.05%
{'WhileTrueBreak': 0.18062000162899494, 'WhileErrFalse': 0.1810499932616949, 'RemainingSlice': 2.9145700042136014, 'LastOccurrence': 0.2049500006251037}
Length: 100000, Ocurrences: 1.977%
{'WhileTrueBreak': 1.9361200043931603, 'WhileErrFalse': 1.7280600033700466, 'RemainingSlice': 254.4725100044161, 'LastOccurrence': 1.9101499929092824}
Length: 100000, Ocurrences: 9.873%
{'WhileTrueBreak': 2.832529996521771, 'WhileErrFalse': 2.9984100023284554, 'RemainingSlice': 1132.4922299943864, 'LastOccurrence': 2.6660699979402125}
Length: 100000, Ocurrences: 25.058%
{'WhileTrueBreak': 5.119729996658862, 'WhileErrFalse': 5.2082200068980455, 'RemainingSlice': 2443.0577100021765, 'LastOccurrence': 4.75954000139609}
Length: 100000, Ocurrences: 49.698%
{'WhileTrueBreak': 9.372120001353323, 'WhileErrFalse': 8.447749994229525, 'RemainingSlice': 5042.717969999649, 'LastOccurrence': 8.050809998530895}