簡體   English   中英

從字符串列表中提取子字符串,其中子字符串由一致的字符限定

[英]Extract substrings from a list of strings, where substrings are bounded by consistent characters

我有一個字符串列表,其中包含不同細菌種類的分類法。 每個列表都有一致的格式:

['d__domain;p__phylum;c__class;o__order;f__family;g__genus;s__species','...','...']

我正在嘗試提取每個列表中每個字符串的屬以找到唯一的屬。 為此,我的想法是制作嵌套的 for 循環,用 ';' 分割每個字符串並使用列表推導搜索“g__”,然后將 g__ 和 append 關聯的屬名刪除到一個新的免費列表中。 我在下面的代碼中嘗試了這個:

finalList = []

for i in range(32586):
    
    outputList = []
    j = 0
    for j in taxonomyData.loc[i,'GTDB Taxonomy'][j]:
        
        ## Access Taxonomy column of Pandas dataframe and split by ;
        taxa = taxonomyData.loc[i,'GTDB Taxonomy'].split(';')
        
        ## Use list comprehension to pull out genus by g__
        genus = [x for x in taxa if 'g__' in x]
        if genus == [] :
            genus = 'None'
            
        ## lstrip off g__
        else:
            genus = genus[0].lstrip('g__')
            
            ## Append genus to new list of genera
            outputList.append(genus)
    ## Append new list of genera to larger list    
    finalList.append(outputList)
    print(finalList)
    break
    
    print(genus)

我測試了這個 for 循環,它成功地將屬從第一個列表的第一個字符串中拉出來,但是當我讓 for 循環運行時,它跳到下一個列表,將所有其他項目留在第一個列表中。 關於如何讓這個循環在進入后續列表之前遍歷第一個列表中的所有字符串的任何建議?

解決了

最終代碼:

finalList = []

for i in range(32586):
        
    ## Access Taxonomy column of Pandas dataframe and split by ;
    if pd.isna(taxonomyData.loc[i,'GTDB Taxonomy']) == True :
        genus_unique = ['None']
        finalList.append(genus_unique)
    else:
        taxa = taxonomyData.loc[i,'GTDB Taxonomy'].split(';')
        
        ## Use list comprehension to pull out genus by g__
        genus_unique = {x[3:] for x in taxa if x.startswith('g__')}
        genus_unique = list(genus_unique)
        
   
        ## Append new list of genera to larger list    
        finalList.append(genus_unique)
print(finalList)

以下是如何使用單個集合理解從列表中獲取唯一的屬條目:

taxa = ['d__abc', 'g__def', 'p__ghi', 'g__jkl', 'd__abc', 'g__def']
genus_unique = {x[3:] for x in taxa if x.startswith('g__')}
print(genus_unique)

結果:

{'def', 'jkl'}

如果需要,您還可以在之后使用list(genus_unique)將其轉換為列表。

暫無
暫無

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

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