簡體   English   中英

從詞到詞的Python數組復制

[英]Python Array Copying From Word To Word

因此,我有一個數組,我想復制此數組中的每個字符串,從它找到我作為條件給出的單詞開始,到另一個具有相同單詞的字符串結束。 例如,如果我有如下數組:

['abcde','Loop: atfg','xyzgh','blabla','blablable Loop','other thing']

例如,我想搜索單詞loop並將每個字符串復制到新數組中,直到再次找到loop。 因此它應該返回如下內容:

['Loop: atfg','xyzgh','blabla','blablable Loop']

任何幫助將不勝感激謝謝

以下代碼查找包含search_str的第一和第二個元素的索引

start_index = my_list.index(next(e for e in my_list if search_str in e))
end_index = my_list.index(next(e for e in my_list[start_index + 1:] if search_str in e))

要了解如何使用它:

my_list = ['trash', 'Loop: 1','2','3','4 Loop', 'more trash']
search_str = "Loop"

start_index = my_list.index(next(e for e in my_list if search_str in e))
end_index = my_list.index(next(e for e in my_list[start_index + 1:] if search_str in e))

result = my_list[start_index:end_index + 1]

它看起來比多行循環更奇怪,但是它有點Python方式:]

通過yield迭代一次源列表:

i = ['abcde','Loop: atfg','xyzgh','blabla','blablable Loop','other thing']

def find_range(items):
    start = False
    for i in items:
        if 'Loop' in i:
            yield i
            if start:
                break

            start = True
        elif start:
            yield i

print list(find_range(i))

可能有更好的方法來解決此問題,但我認為一個好的老式循環在此處效果最好:

def word_copy(lst, search):
    res = []
    for item in lst:
        if res:
            res.append(item)
            if search in item:
                return res

        elif search in item:
            res.append(item)

嘗試做這樣的事情:

list = ['abcde','Loop: atfg','xyzgh','blabla','blablable Loop','other thing']
if any("loop" in l for l in list):

遍歷列表,查找第一個匹配項,然后查找第二個匹配項:

input = ['abcde','Loop: atfg','xyzgh','blabla','blablable Loop','other thing']
target = 'Loop'

start_index, end_index = None, None
for i in input:
    if target in i:
        if start_index is None:
             start_index = input.index(i)
             continue
        end_index = input.index(i)
        break

output = input[start_index : end_index + 1]

與您的清單:

list = ['abcde','Loop: atfg','xyzgh','blabla','blablable Loop','other thing']

我想你可以嘗試做這樣的事情,以便找到數組中的位置:

ixs = [i for i, word in enumerate(list) if word.startswith('Loop') or word.endswith('Loop')]

然后,您只需要分割列表:

res = list[ixs[0]:ixs[1]+1]

希望這可以對您有所幫助。

我看到有一些花哨的單線解決方案。 :)然而,我喜歡那些蠻橫的人,這些人看起來更了解:

>>> my_list = ['abcde','Loop: atfg','xyzgh','blabla','blablable Loop','other thing']
>>> search_str = "(Loop)+"
>>> out = []
>>> count = 0
>>> for s in my_list:
...     if count == 2:
...         break
...     m = re.search(search_str, s)
...     if m != None:
...         count += 1
...     if count >= 1:
...         out.append(s)
...
>>> out
['Loop: atfg', 'xyzgh', 'blabla', 'blablable Loop']
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM