2

我有一个简单的问题,如果我在 python 中有一个字符串数组: ['a', 'b', 'c', 'd'] 有没有办法可以比较另一个字符串以及它是否存在于数组中删除该值及其之后的所有内容?我是 python 新手,对语法不太熟悉,但对伪代码不太熟悉:

s = 'b'
array = ['a', 'b', 'c', 'd']

if b exists in array
    remove b and elements after

所以新数组只是['a']。任何帮助将非常感激!

4

2 回答 2

7
s = 'b'
array = ['a', 'b', 'c', 'd']

if s in array:
    del array[array.index(s):]
于 2013-09-21T17:50:39.907 回答
2

备择方案:

from itertools import takewhile
array = takewhile(lambda x: x != "b", array)
# then if array must be a list (we can already iterate through it)
array = list(array)

或者

if "b" in array:
    del array[array.index("b"):]

或者

try:
    del array[array.index("b"):]
except ValueError:
    # "b" was not in array
    pass
于 2013-09-21T17:51:19.760 回答